ES6提出Promise, 同事包含
Promise.all全部成功,否则报错Promise.race第一个结果,无论成功失败Promise.then成功回调Promise.catch失败回调
ES9补充
Promise.finally处理结果之后最后再执行的
ES11补充
Promise.allSettled所有都完成,无论成功失败
ES12补充
Promise.any第一个成功,都不成功就报错 (与**race**区别)new Promise((resolve, reject) => {if (xxx) {resolve('Yes')}reject('No')}).then(cb1).catch(cb2).finally(cb3)
ES9补充了 **for await of**
- 在 async 函数中使用:
** for await (let i of [ p1, p2 ... ]) { ... }** - 与
**Promise.all**区别是:- 不用等待所有,会按顺序返回
- 当有拒绝时,拒绝项之后的不执行,之前的仍按顺序返回
``javascript function fn (time) { return new Promise((resolve, reject) => { setTimeout(() => { if (time === 5000) reject('失败') resolve(${time}毫秒后我成功啦!!!`) }, time) }) }
async function asyncFn () { const arr = [fn(1000), fn(3000), fn(1000), fn(2000), fn(5000)] for await (let x of arr) { console.log(x) } }
asyncFn()
```
