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