async和await 优雅处理异步

简介: async和await 优雅处理异步

文章目录

function delay(word) {
    return new Promise((resolve, reject) => {
        setTimeout(()=>{
            resolve('hello ' + word)
        }, 2000)
    })
}
async function start(){
    const word1 = await delay('孙悟空')
    console.log(word1)
    const word2= await delay('猪八戒')
    console.log(word2)
    const word3 = await delay('沙悟净')
    console.log(word3)
}
start()

执行结果:


没有嵌套地狱,也没有promise调用的多个括号和then,用变量就可接收异步的返回值,然后像同步代码一样书写,赞!!

目录
打赏
0
0
0
0
15
分享
相关文章
async/await
async/await
50 0
|
7月前
|
C#
C# async await 异步执行方法
C# async await 异步执行方法
70 0
等一下!深入async/await的异步世界
等一下!深入async/await的异步世界
122 1
处理异步请求的 async/await 和 promise
处理异步请求的 async/await 和 promise
106 0
Async/Await 在何时该使用,何时不使用
使用 async/await 是在处理异步操作时的一种更简洁、易读的方式,它基于 Promise,并且可以使异步代码看起来像同步代码一样编写。然而,并不是所有情况下都需要使用 async/await。
270 0

热门文章

最新文章

AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等