消耗等待的结果并返回等待的结果之间有什么区别?
我对以下两个代码片段感到有些困惑:
async function f() {
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("done!"), 1000)
});
let result = await promise; // wait until the promise resolves (*)
return result;
}
console.log(f()); //prints Promise { <pending> } at once then wait for 1 second before terminating
我
async function f() {
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("done!"), 1000)
});
let result = await promise; // wait until the promise resolves (*)
console.log(result);
}
f(); //waits for 1 second and prints done! before terminating
期望上面的两个代码片段产生相同的结果,例如打印! 1秒钟后到达控制台。是什么使第一个代码段返回
I am a bit confused by the two following code snippets:
async function f() {
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("done!"), 1000)
});
let result = await promise; // wait until the promise resolves (*)
return result;
}
console.log(f()); //prints Promise { <pending> } at once then wait for 1 second before terminating
And
async function f() {
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("done!"), 1000)
});
let result = await promise; // wait until the promise resolves (*)
console.log(result);
}
f(); //waits for 1 second and prints done! before terminating
I was expecting the two code snippets above to produce the same result, e.g. print done! to the console after 1 second. What made the first code snippet return
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
两个代码片段在同一点返回。
等待
关键字在RHS上得到承诺时,它使其属于睡眠的功能直到该诺言解决。同时,调用功能获得了
f
返回的承诺,并继续运行。这就是使用
async
函数的重点:当他们处理某些异步时,它们不会阻止。Both code snippets return at the same point. The
await
keyword, when it gets a promise on the RHS, makes the function it belongs to go to sleep until that promise settles.Meanwhile, the calling function gets the promise returned by
f
and continues running.That's the point of using
async
functions: They don't block when they are dealing with something asynchronous.