1.期约(Promise)
Promise解决回调地狱(链式调用)
let l = new Promise((resolve, reject) => resolve())
l.then(res => {
console.log(1)
}).then(res => {
return new Promise((resolve, reject) => {
console.log(2)
setTimeout(resolve, 1000, 3)
})
}).then(res => {
console.log(res) // 3
})
// 1
// 2
// 3
/* 在then回调函数返回期约(Promise),则之后的then调用会等待结果返回(resolve()执行)后,再执行 */
2.async/await使用
async使用
async function pro() {
console.log(1)
return 3
}
console.log(pro()) // Promise {<fulfilled>: 3}
pro().then(console.log)
console.log(2)
// 1
// 2
// 3
await使用
async function foo() {
console.log(2)
console.log(await Promise.resolve(6))
console.log(7)
}
async function bar() {
console.log(4)
console.log(await 8)
console.log(9)
}
console.log(1)
foo()
console.log(3)
bar()
console.log(5)
// 1
// 2
// 3
// 4
// 5
// 6
// 7
// 8
// 9
上面例子的执行顺序
- 打印1
- 调用异步函数foo()
- 在foo中打印2;
- 遇到await关键字暂停执行,向消息队列中添加一个待执行任务(Promise.resolve(6))
- 同步线程打印3
- 执行异步函数bar()
- 在bar中打印4
- 遇到await关键字暂停执行,向消息队列中添加一个待执行任务(8)
- 同步线程打印5
- 同步线程执行完毕
- 从消息队列取出恢复foo执行的任务
- 打印6
- 打印7
- 从消息队列取出恢复bar执行的任务
- 打印8
- 打印9