Promise 是异步编程解决方案,Promise对象有2个特点,
- 1.对象的状态不受外部影响。有三种状态,pending fulfilled rejected
- 2.状态一旦改变,就不会再变。 比如 pending -> fulfilled || pending -> rejected
Promise.all
全部fulfilled -> then,
有一个rejected 就会catch。不会等待后面执行1
2
3
4
5
6
7
8
9
10
11const resolved = Promise.resolve(42);
const rejected = Promise.resolve(-1);
const rejected1 = Promise.reject(88);
const p1 = new Promise(function (resolve, reject) {
setTimeout(() => reject(new Error('fail')), 2000)//不执行
})
Promise.all([resolved, rejected,rejected1,p1]).then((res)=>{
console.log(res)
}).catch(e=>{
console.log(e)
});
Promise.allSettled
1 | const resolved = Promise.resolve(42); |
Promise.any()
1 | const resolved = Promise.resolve(42); |
Promise.race
1 | // 只要任意一个promise状态改变就会返回状态给p |
手动完成一个promise
1 | // 原型 |