学会使用async/await

2022-12-19 0 850

async/await

句法如是说和 Promise 的亲密关系触发器其本质for…of

有许多 async 的丘托韦,比如

async 间接回到,是甚么?async间接回到 promise?await 前面不加 promise?

之类,须要找寻两个规律性

句法如是说

用并行的形式,撰写触发器。

function loadImg(src) { const promise = new Promise((resolve, reject) => { const img = document.createElement(img) img.onload = () => { resolve(img) } img.onerror = () => { reject(new Error(`相片读取失利 ${src}`)) } img.src = src }) return promise } async function loadImg1() { const src1 = http://www.imooc.com/static/img/index/logo_new.png const img1 = awaitloadImg(src1)return img1 } async function loadImg2() { const src2 = https://avatars3.githubusercontent.com/u/9583120 const img2 = await loadImg(src2) return img2 } (async function () { // 注意:await 必须放在 async 函数中,否则会报错 try { // 读取第一张相片 const img1 = await loadImg1() console.log(img1) // 读取第二张相片 const img2 = await loadImg2() console.log(img2) } catch (ex) { console.error(ex) } })()

和 Promise 的亲密关系

async 函数回到结果都是 Promise对象(如果函数内没回到Promise ,则自动封装一下)

async function fn2() { return new Promise(() => {}) } console.log( fn2() ) async function fn1() { return 100 } console.log( fn1() ) // 相当于 Promise.resolve(100)

await 前面跟 Promise 对象:会阻断后续代码,等待状态变为 resolved

await 后续跟非 Promise 对象:会间接回到

(async function () { const p1 = new Promise(() => {}) await p1 console.log(p1) // 不会执行 })() (async function () { const p2 = Promise.resolve(100) const res = await p2 console.log(res)// 100 })() (async function () { const res = await 100 console.log(res) // 100 })() (async function () { const p3 = Promise.reject(some err) const res = await p3 console.log(res) // 不会执行 })() try…catch 捕获 rejected 状态(async function () { const p4 = Promise.reject(some err) try { const res = await p4 console.log(res) } catch (ex) { console.error(ex) } })()

总结来看:

async 封装 Promiseawait 处理 Promise 成功try…catch 处理 Promise 失利

触发器本质

await 是并行写法,但其本质还是触发器调用

async function async1 () { console.log(async1 start) await async2() console.log(async1 end) // 关键在这一步,它相当于放在 callback 中,最后执行 } async function async2 () { console.log(async2) } console.log(script start) async1() console.log(script end)

即,只要遇到了 await ,前面的代码都相当于放在 callback 里。

for…of

定时算乘法

// 定时算乘法 function multi(num) { return new Promise((resolve) => { setTimeout(() =>{ resolve(num * num) },1000) }) } // // 采用 forEach ,是 1s 之后打印出所有结果,即 3 个值是一起被计算出来的 // function test1 () { // const nums = [1, 2, 3]; // nums.forEach(async x => { // const res = await multi(x); // console.log(res); // }) // } // test1(); // 采用 for…of ,可以让计算挨个串行执行 async function test2 () { const nums = [1, 2, 3]; for (let x ofnums) {// 在 for…of 循环体的内部,遇到 await 会挨个串行计算 const res = await multi(x) console.log(res) } } test2()

执行 async 函数执行回到的是 Promise 对象

await 相当于 Promise 的 then

try…catch 可捕获异常,代替 Promise 的 catch

学会使用async/await

右上图解读: async回到Promise,await回到then,await前面报错会终止执行,可以用try…catch来捕获

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务