简体   繁体   English

JavaScript异步/等待未正确等待?

[英]JavaScript async/await not awaiting properly?

I'm having an issue with JavaScript's async/await functions. 我在JavaScript的async / await函数方面遇到问题。 This is happening on an internal application that I can't share the source for, but I put together a quick generic reproduction of my issue: 这是在我无法共享其源代码的内部应用程序上发生的,但是我将我的问题进行了快速的通用复制:

 function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } async function baz(input) { console.log("4"); await sleep(1000); console.log("5"); return input; } async function bar(input) { console.log("3"); return await baz(input); } async function foo() { console.log("2"); const foo = await bar("foo"); return foo; } console.log("1"); foo(); console.log("6"); 

I would expect this to return the following with a one second wait between 4 and 5 : 我希望这会在45之间等待一秒钟,返回以下内容:

1
2
3
4
5
6
"foo"

Instead, after trying this in the console in Chrome 64.0.3282.167 and Firefox 58.0.2 I receive this: 相反,在Chrome 64.0.3282.167和Firefox 58.0.2中的控制台中尝试此操作后,我收到以下消息:

1
2
3
4
6
undefined
5

Please can someone point out where I'm going wrong in this? 请有人指出我在这方面出错了吗?

The top-level is running synchronously (as it always does) - it doesn't wait for foo(); 顶层正在同步运行(始终如此)-它不等待foo(); to resolve before continuing to console.log("6"); 在继续console.log("6");之前解决console.log("6"); . Wrap the calling of foo in something async and await it. foo的调用包装在异步中,然后await它。 You also need to save the return value of foo if you want to display its later: 如果要稍后显示foo还需要保存foo的返回值:

 function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } async function baz(input) { console.log("4"); await sleep(1000); console.log("5"); return input; } async function bar(input) { console.log("3"); return await baz(input); } async function foo() { console.log("2"); const foo = await bar("foo"); return foo; } (async () => { console.log("1"); const str = await foo(); console.log("6"); console.log(str); })(); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM