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,用变量就可接收异步的返回值,然后像同步代码一样书写,赞!!

相关文章
|
2月前
|
前端开发 JavaScript
什么是 async、await ?
什么是 async、await ?
|
7月前
|
前端开发 JavaScript
|
20天前
|
前端开发 JavaScript
async/await
async/await
16 0
|
2月前
|
监控 前端开发 JavaScript
等一下!深入async/await的异步世界
等一下!深入async/await的异步世界
50 1
|
3月前
|
前端开发 JavaScript
|
8月前
|
前端开发 API
Async/Await 在何时该使用,何时不使用
使用 async/await 是在处理异步操作时的一种更简洁、易读的方式,它基于 Promise,并且可以使异步代码看起来像同步代码一样编写。然而,并不是所有情况下都需要使用 async/await。
104 0
|
8月前
|
前端开发 JavaScript
async、await 实现原理
async、await 实现原理
52 1
|
消息中间件 前端开发 JavaScript
ES8 中的 async/await —— 异步函数
ES8 中的 async/await —— 异步函数
150 0
|
前端开发
async/await详解
async/await详解
257 0
async/await详解