我有一些使用JavaScript Async/等待的代码:
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");
根据关于异步/等待:
异步函数可以包含暂停的等待表达
执行异步功能,并等待通过的承诺
分辨率,然后恢复异步函数的执行和
返回解决值。
我期望以下输出:
dosomething1
//wait for 6 seconds
dosomething2
Promise { <state>: "fulfilled", <value>: "returnfromfun1" }
hello
但是实际输出是:
dosomething1
Promise { <state>: "pending" }
hello
//wait for 6 seconds
dosomething2
Fun1在“等待”线上返回。我是否误解了官方文件中的描述?而且看来我从未获得fun1(“ returnfromfun1”)的返回值。
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");
According to the official document about async/await:
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.
I expect the following output:
dosomething1
//wait for 6 seconds
dosomething2
Promise { <state>: "fulfilled", <value>: "returnfromfun1" }
hello
But the actual output is:
dosomething1
Promise { <state>: "pending" }
hello
//wait for 6 seconds
dosomething2
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").
发布评论
评论(1)
您必须以略有不同的方式阅读引用的部分:
仅仅是异步函数本身暂停了执行,当时称为它的函数。
如果您想到同步的呼叫站,则会发生的是,异步函数上下文被弹出并存储在其他地方:
,是的。在那一刻,它返回了一个诺言,即在异步函数返回(在某个时候继续执行之后)时就可以解决。
当承诺解决时,您可以得到它:
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:
Yes, exactly. In that moment it returns a promise, that resolves when the async function returns (after it continued execution somewhen).
You can get it when the promise resolves: