// 通过构造函数 Promise 生成一个 promise 对象
var promise = new Promise(function (resolve, reject) {
resolve(value);
reject(error);
});
// promise 对象拥有的实例函数有 then,catch
// then 函数用来指定 resolve 后的回调函数,当然你也可以传入第二个参数用于指定发生错误时的回调函数
// 一般我们调用 catch 来指定其产生错误的回调函数,catch 为 then 的别名
promise
.then(onFulfilled, onRejected)
.catch(onRejected)
静态方法,为 new Promise() 的快捷方式
Promise.resolve(value)
//equal to
new Promise(function (resolve) { resolve(value); });
// Promise.resolve() 还可用于将 thenable 对象转换为 promise 对象
Promise.reject(error)
//equal to
new Promise(function (_, reject) { reject(error); });
如果对异步回调函数进行同步调用的话,处理顺序可能会与预期不符,可能带来意料之外的后果
promise 通过 then 添加的回调函数执行属于 microtasks。
每次调用 then、catch 方法都会返回一个新创建的 promise 对象
Promise
.resolve()
.then(function () { return 5; })
.then(function (value) { console.log(value); })
.catch(function (error) { console.log('error >>>', error); });
// 5
Promise
.resolve()
.then(function () {
return new Promise(function (resolve, reject) {
reject('error');
resolve(5);
});
}).
.then(function (value) { console.log(value); })
.catch(function (error) { console.log(error); });
// "error"
Promise
.all[promiseTask1, promiseTask2] // task1 task2 同时开始执行
.then(function (results) {
// results 为 task1 和 task2 的顺序返回结果的数组
});
Promise
.race[promiseTask1, promiseTask2] // task1 task2 同时开始执行
.then(function (fastTaskResult) {
// 得到的值列表中最先返回的值,但是不影响其他任务执行
});
Difference between microtask and macrotask within an event loop context Promise 迷你书