const p = Promise.all([p1, p2, p3]);Promise.all()方法接受一个数组作为参数,p1、p2、p3都是 Promise 实例
const p = Promise.race([p1, p2, p3]);上面代码中,只要p1、p2、p3之中有一个实例率先改变状态,p的状态就跟着改变。那个率先改变的 Promise 实例的返回值,就传递给p的回调函数。
const resolved = Promise.resolve(42); const rejected = Promise.reject(-1); const allSettledPromise = Promise.allSettled([resolved, rejected]); allSettledPromise.then(function (results) { console.log(results); });Promise.any()
var resolved = Promise.resolve(42); var rejected = Promise.reject(-1); var alsoRejected = Promise.reject(Infinity); Promise.any([resolved, rejected, alsoRejected]).then(function (result) { console.log(result); // 42 }); Promise.any([rejected, alsoRejected]).catch(function (results) { console.log(results); // [-1, Infinity] });Promise.resolve()
有时需要将现有对象转为 Promise 对象,Promise.resolve()方法就起到这个作用。
const jsPromise = Promise.resolve($.ajax('/whatever.json'));
Promise.resolve('foo') // 等价于 new Promise(resolve => resolve('foo'))Promise.reject()
const p = Promise.reject('出错了'); // 等同于 const p = new Promise((resolve, reject) => reject('出错了')) p.then(null, function (s) { console.log(s) }); // 出错了上面代码生成一个 Promise 对象的实例p,状态为rejected,回调函数会立即执行。