javascript async/await实际如何工作? [英] How does javascript async/await actually work?

查看:55
本文介绍了javascript async/await实际如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些使用javascript async/await的代码:

I have some code using javascript async/await:

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function fun1()
{
     console.log("dosomething1");
     await sleep(6000);
     console.log("dosomething2");
     return "returnfromfun1";
}
console.log(fun1());
console.log("hello");

根据官方文档关于异步/等待:

异步函数可以包含一个await表达式,该表达式会暂停执行异步函数并等待传递的Promise的解决,然后恢复异步函数的执行和返回解析值.

An async function can contain an await expression that pauses the execution of the async function and waits for the passed Promise's resolution, and then resumes the async function's execution and returns the resolved value.

我希望得到以下输出:

dosomething1
//wait for 6 seconds
dosomething2
Promise { <state>: "fulfilled", <value>: "returnfromfun1" }
hello

但是实际输出是:

dosomething1
Promise { <state>: "pending" }
hello
//wait for 6 seconds
dosomething2

fun1似乎在"await"行返回.我是否误解了官方文件中的描述?看来我从来没有得到过fun1("returnfromfun1")的返回值.

It seems fun1 returns at the "await" line. Did I misunderstand the description in the official document? And it seems I never get the return value of fun1("returnfromfun1").

推荐答案

您必须稍微不同地阅读引用的部分:

You have to read the quoted part slightly differently:

异步函数可以包含一个等待表达式,该表达式会暂停异步函数的执行

异步函数本身会暂停执行,然后调用它的函数会继续执行.

Just the async function itself pauses execution, the function that called it goes on then.

如果您想到的是同步调用栈,那么将会发生异步函数上下文被弹出并存储在其他地方的情况:

If you think of a synchronous callstack, what happens is that the asynchronous functions context gets popped of, and stored somewhere else:

 stack: [init] -> [async] fun1 -> sleep -> setTimeout
  // The promise gets returned from sleep
 stack: [init] -> [async] fun1
 // The async function gets popped of
 stack: [init]
 hidden: [async] fun1
 // synchronous execution ends
 stack: -
 hidden: [async] fun1
 // the timer triggers, the promise gets resolved
 stack: setTimeout callback
 hidden: [async] fun1
 // synchronous execution ends
 stack: -
 hidden: [async] fun1
 // the promise resolves, the async fun1 context gets moved onto the stack
 stack: [async] fun1

fun1似乎在"await"行中返回

It seems fun1 returns at the "await" line

是的,完全正确.在那一刻,它返回一个Promise,该Promise会在异步函数返回时(在其继续执行之后)解析.

Yes, exactly. In that moment it returns a promise, that resolves when the async function returns (after it continued execution somewhen).

似乎我永远都没有得到fun1("returnfromfun1")的返回值.

And it seems I never get the return value of fun1("returnfromfun1").

当诺言解决时,您可以得到它:

You can get it when the promise resolves:

  fun1().then(result => console.log(result));

这篇关于javascript async/await实际如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆