期约与异步函数async/await

96 阅读1分钟

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. 打印1
  2. 调用异步函数foo()
  3. 在foo中打印2;
  4. 遇到await关键字暂停执行,向消息队列中添加一个待执行任务(Promise.resolve(6))
  5. 同步线程打印3
  6. 执行异步函数bar()
  7. 在bar中打印4
  8. 遇到await关键字暂停执行,向消息队列中添加一个待执行任务(8)
  9. 同步线程打印5
  10. 同步线程执行完毕
  11. 从消息队列取出恢复foo执行的任务
  12. 打印6
  13. 打印7
  14. 从消息队列取出恢复bar执行的任务
  15. 打印8
  16. 打印9