我在学习 JS 异步时遇到了 Async/Await。然后,我遇到了这段代码:
function scaryClown() {
return new Promise(resolve => {
setTimeout(() => {
resolve('🤡');
}, 2000);
});
}
async function msg() {
const msg = await scaryClown();
console.log('Message:', msg);
}
msg(); // Message: 🤡 <-- after 2 seconds
因此,我对上面的代码有疑问。首先,如果函数本身只返回未定义的 Promise,即函数没有显式使用 return 关键字,那么异步函数 msg() 如何返回消息值。其次,await 是否返回 Promise 还是从 Promise 中解包的值本身?
最佳答案
function scaryClown() {
return new Promise(resolve => {
setTimeout(() => {
resolve('🤡');
}, 2000);
});
}
上面的函数是一个在调用时返回一个 Promise 的函数,但只有 2 秒后才会被解析。
async function msg() {
const msg = await scaryClown();
console.log('Message:', msg);
}
上面的函数是异步函数,它等待 promise 得到解决(在您的情况下,2秒后),然后只有 console.log() 触发。
注意:无论 Promise 和异步函数如何,函数 msg() 下面的任何代码行都会被执行。
运行代码片段
function scaryClown() {
return new Promise(resolve => {
setTimeout(() => {
resolve('🤡');
}, 2000);
});
}
async function msg() {
console.log(scaryClown()); // try without await, so it will not wait for the result and prints first, but an unresolved promise
const msg = await scaryClown(); // actual result which is resolved, because we awaited
console.log('Message:', msg); // Prints once the resolved value is available.
}
msg(); //executes first but only prints the value once it is resolved.
console.log('I will continue executing irrespective of async func msg()');
关于javascript - JS 中的 Async/Await 混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59872653/