Porimise.resolve(obj) Promise.reject(obj)
- obj是非Promise对象,其状态PromiseState一定是 fulfilled
- obj是Promise对象, 则根据obj的状态PromiseState是 fulfilled或 rejected 来决定整体的
- resolve或 reject 本质是把 PromiseState 从 pending –> fulfilled/ rejected
- 状态不为pending 就会调用then
1 2 3 4 5
| const p = Promise.resolve( new Promise((resolve, reject) => { reject("ok!"); }) );
|
1 2 3 4 5 6 7 8 9 10 11 12 13
| p.then((res) => { console.log("res",res); }, (err)=> { console.log("err",err) })
p.then((res) => { console.log("res",res); }).catch(err=> { console.log("err",err) })
|
Promise.all(Promise[])
一次性执行多个异步,返回数组
1 2 3 4 5 6 7 8 9
| const p1 = Promise.resolve('p1'); const p2 = Promise.resolve('p2') const p3 = Promise.resolve('p3'); Promise.all([p1,p2,p3]).then(results=> { console.log(results) }).catch(errs=> { console.log(errs) })
|
1 2 3 4 5
| const p1 = Promise.resolve('p1'); const p2 = Promise.reject('p2') const p3 = Promise.resolve('p3');
|
Promise.race(Promise[])
返回遇到的第一个状态转为成功的promise对象
1 2 3 4 5 6 7
| const a1 = Promise.reject("a1"); const a2 = Promise.resolve("a2"); const a3 = Promise.resolve("a3"); const a = Promise.race([a1,a2,a3]) console.log(a)
|
1 2 3 4 5 6
| const a1 = Promise.reject("a1").catch(); const a2 = Promise.resolve("a2"); const a3 = Promise.resolve("a3"); const a = Promise.race([a1,a2,a3]) console.log(a)
|
.then()链式调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| const p = new Promise((resolve, reject) => { resolve("resolve"); }) p.then(result => { console.log(result) }).then(res => { console.log(res) return new Promise((resolve, rejedct) => { resolve('resolve2') }) }).then(res => { console.log(res) return Promise.reject('reject') }).catch(err=>console.log(err))
|
异常穿透
1 2 3 4 5 6 7 8 9 10 11 12
| const p = Promise.resolve('p') p.then(result => { console.log(result) }).then(res => { console.log(res) return Promise.reject("reject 1") }).then(res => { console.log('执行了') return Promise.reject("reject 2") }).catch(err => { console.log("err", err) })
|
中断链式调用
当PromiseState: pending时,不会进入then()
1 2 3 4 5 6 7 8
| new Promise(resolve => { resolve("hello") }).then(res => { console.log("then") return new Promise(() => { }) }).then(res => { console.log("then2") })
|
async & await
async
- async 返回Promise对象
- async function fn(){} 返回结果由fn的结果决定
await
- 右边一般是Promise对象
- 如果表达式是Promise对象, 返回Promise成功的值
- 如果表达式是其他值,直接返回
注意: i. await必须写在async中
ii. await右边promise失败(状态为rejected)会抛出异常,需要用try catch
iii. await 不可以在文件顶层使用(用立即执行函数包裹)
1 2 3 4 5 6 7 8 9 10 11
| (async function () { let asyncFn2 = function () { return new Promise((resolve, reject) => { setTimeout(() => { console.log('timeout') resolve('ok') }, 1500); }) } console.log(await asyncFn2()) })()
|