繁体   English   中英

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

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

考虑以下代码:

 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. 有没有解决的办法?

您需要await f() 这是一个例子:

 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); })();

您需要等待 f function 返回的 promise。 这就是为什么它打印 promise 而不是结果的原因。

console.log(await f());

暂无
暂无

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

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