对async 和 await的理解

it2023-12-20  62

//async await 简单来说就是把异步执行 转成同步代码。 // async 必须修饰函数,加上async,返回promise对象 // await 必须出现在async修饰的函数中,wait的是resolve(data)的消息,并把数据data返回。

function say() { return new Promise(function (resolve, reject) { // 延时器1s之后,执行 setTimeout(function () { let age = 26 resolve(`hello,今年我 ${age} 岁`); }, 1000) }) } async function demo() { // 等待promise执行完成,并返回值 // 不加await 在调用say()时,延时器异步执行 date还没有值得时候就输出了 所以显示是promise(pending)正在等待的状态,当添加上await时 等待say()这个promise执行完毕再输出 let data = await say(); console.log(data); } // demo();
最新回复(0)