之前总是去看promise的源码博客,或者手动实现一个promise,理论疏忽了promise的一些根本用法,明天就略微总结下吧。

1、Promise.resolve
Promise.resolve(42)理论能够看成一下代码的语法糖,
同理Promise.reject(new Error('出错啦'))

new Promise(function(resolve){    resolve(42);});

Promise.resolve也返回了一个promise对象,因而能够调用.then办法

Promise.resolve(42).then(function(value){    console.log(value);});

2、Thenable
Thenable指的是一个具备 .then 办法的对象。
Promise.resolve 办法另一个作用就是将 thenable 对象转换为promise对象

3、new Promise回调函数是同步执行代码,而.then是异步回调(微工作)

4、promise的.then和.catch办法能够链式调用
.then或.catch办法都会创立并返回一个新的promise对象(因为只有promise对象上才有then和catch办法,这样链式调用就很好了解了)
比方chain 调用
resolve → then → then → then 的程序执行,并且传给每个 then 办法的 value 的值都是前一个promise对象通过 return 返回的值。

var aPromise = new Promise(function (resolve) {    resolve(100);});var thenPromise = aPromise.then(function (value) {    console.log(value);});var catchPromise = thenPromise.catch(function (error) {    console.error(error);});console.log(aPromise !== thenPromise); // => trueconsole.log(thenPromise !== catchPromise);// => true

5、promise.all
当数组里的promise全副resolve的时候,then回调就会触发(同理 全副reject后才会触发catch回调)
promise.all([p1,p2,...pn]).then()
传递给 Promise.all 的promise并不是一个个的程序执行的,而是同时开始、并行执行的。
而且promise.all的后果resp外部的程序是跟promise的数组程序统一的,哪怕p2比p1先执行完

6、promise.race
race有竞速的意思
即谁先执行完,race就then回调
只有有一个promise对象进入 FulFilled 或者 Rejected 状态的话,就会持续进行前面的解决。

摘抄:
1.promise