关于javascript:async-函数的使用

48次阅读

共计 2159 个字符,预计需要花费 6 分钟才能阅读完成。

根本应用

async 函数返回的是一个 Promise,可能进行 Promise 的相干操作, 函数外部返回的后果会成为 then 办法回调函数的参数

async function asyncfunc(){return "这是一个 async 函数"}
asyncfunc()
asyncfunc().then(function(info){console.log(info)})

当函数执行中遇到 await,需等异步操作实现,才会执行前面的代码

async function asyncfunc() {let now = new Date().getTime();
        await new Promise((resolve, reject) => {setTimeout(() => {resolve()
            }, 2000)
        })
        console.log(new Date().getTime() - now)
    }

函数外部错处,返回的 promise 状态为 rejected

 async function asyncfunc(){console.log(err)
    }

async 函数返回的 Promise 只有函数外部中 await 后的异步事件执行完后,才会扭转,除非中途 return 或者出错

(async function() {await new Promise((resolve, reject) => {console.log("第一个 await")
            resolve()})
        await new Promise((resolve, reject) => {console.log("第二个 await")
            resolve()})
        await new Promise((resolve, reject) => {console.log("第三个 await")
            resolve()})
    })().then(info=>{console.log("触发 then")})

(async function() {await new Promise((resolve, reject) => {console.log("第一个 await")
            resolve()})
        return "执行 return"
        await new Promise((resolve, reject) => {console.log("第二个 await")
            resolve()})
        await new Promise((resolve, reject) => {console.log("第三个 await")
            resolve()})
    })().then(info=>{console.log("触发 then")})

(async function() {await new Promise((resolve, reject) => {console.log("第一个 await")
            resolve()})
        throw new Error("出错了")
        await new Promise((resolve, reject) => {console.log("第二个 await")
            resolve()})
        await new Promise((resolve, reject) => {console.log("第三个 await")
            resolve()})
    })()

await 后的 Promise 状态变为 rejected 时,会被 catch 接管到

(async function() {await new Promise((resolve, reject) => {reject("状态变为 rejected")
        })
    })().catch(info => {console.log(info)
    })

任意一个 await 后的 Promise 函数变为 rejecte,async 函数的执行就会中断,若想继续执行,可应用 try{}catch(e){} 捕捉

(async function() {await new Promise((resolve, reject) => {reject("状态变为 rejected")
        })
        await new Promise((resolve, reject) => {console.log("第二个 await")
            resolve()})
    })().catch(info => {console.log(info)
    })

(async function() {
        try {await new Promise((resolve, reject) => {reject("状态变为 rejected")
            })
        } catch (err) {console.log("捕捉" + err)
        }

        await new Promise((resolve, reject) => {console.log("第二个 await")
            resolve()})
    })().catch(info => {console.log(info)
    })


另一种办法是将 await 前面的 Promise 增加 catch

(async function() {await new Promise((resolve, reject) => {reject("状态变为 rejected")
        }).catch(info => {console.log("捕捉" + info)
        })
        await new Promise((resolve, reject) => {console.log("第二个 await")
            resolve()})
    })().catch(info => {console.log(info)
    })

正文完
 0