简体   繁体   English

异步 function 在返回之前不等待等待

[英]Async function doesn't wait with await before returning

Consider the following code:考虑以下代码:

 const getName = () => new Promise(resolve => setTimeout(resolve, 1000, 'xxx')); f = async () => { let name = await getName(); console.log(name); return name; } console.log(f());

The function will wait before printing "name" but it will still return the promise instead of the result and won't print the correct output outside the function. The function will wait before printing "name" but it will still return the promise instead of the result and won't print the correct output outside the function. Is there a way around this?有没有解决的办法?

You need to await for f() .您需要await f() Here is an example:这是一个例子:

 const getName = () => new Promise(resolve => setTimeout(resolve, 1000, 'xxx')); const f = async () => { const name = await getName(); console.log("1. "+name); return name; } const run = (async () => { const ret = await f(); console.log("2. "+ret); })();

You need to await the promise returned by the f function.您需要等待 f function 返回的 promise。 That is why its printing a promise instead of a result.这就是为什么它打印 promise 而不是结果的原因。

console.log(await f());

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

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