消耗等待的结果并返回等待的结果之间有什么区别?

发布于 2025-01-21 11:13:23 字数 754 浏览 0 评论 0原文

我对以下两个代码片段感到有些困惑:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

蓝天 2025-01-28 11:13:23

是什么使第一个代码段返回

两个代码片段在同一点返回。 等待关键字在RHS上得到承诺时,它使其属于睡眠的功能直到该诺言解决。

同时,调用功能获得了f返回的承诺,并继续运行。

这就是使用async函数的重点:当他们处理某些异步时,它们不会阻止

What made the first code snippet return

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文