首先要了解 promise :promise
代码一,了解 async 与 promise 的区别:
async function helloAsync(){
return "helloAsync";
}
console.log(helloAsync()) // Promise {<resolved>: "helloAsync"}
helloAsync().then(v=>{
console.log(v); // helloAsync
})
async 里 return 相当于 promise 的 resolve(),所以 promise 状态变成 fulfilled,这时就会跳到 .then() 里进行执行。
代码二,了解 await 的使用:
function testAwait(){
return new Promise((resolve) => {
setTimeout(function(){
console.log("testAwait");
resolve();
}, 1000);
});
}
async function helloAsync(){
await testAwait();
console.log("helloAsync");
}
helloAsync();
3 秒后打印: