以前老是去看promise的源码博客,或者手动实现一个promise,实际忽略了promise的一些基本用法,今天就稍微总结下吧。html
一、Promise.resolve
Promise.resolve(42)实际能够当作一下代码的语法糖,
同理Promise.reject(new Error('出错啦'))git
new Promise(function(resolve){ resolve(42); });
Promise.resolve也返回了一个promise对象,所以能够调用.then方法数组
Promise.resolve(42).then(function(value){ console.log(value); });
二、Thenable
Thenable指的是一个具备 .then 方法的对象。
Promise.resolve 方法另外一个做用就是将 thenable 对象转换为promise对象promise
三、new Promise回调函数是同步执行代码,而.then是异步回调(微任务)异步
四、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); // => true console.log(thenPromise !== catchPromise);// => true
五、promise.all
当数组里的promise所有resolve的时候,then回调就会触发(同理 所有reject后才会触发catch回调)
promise.all([p1,p2,...pn]).then()
传递给 Promise.all 的promise并非一个个的顺序执行的,而是同时开始、并行执行的。
并且promise.all的结果resp内部的顺序是跟promise的数组顺序一致的,哪怕p2比p1先执行完code
六、promise.race
race有竞速的意思
即谁先执行完,race就then回调
只要有一个promise对象进入 FulFilled 或者 Rejected 状态的话,就会继续进行后面的处理。htm
摘抄:
1.promise对象