[英]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.