![](/img/trans.png)
[英]React router 4: How to wait for a promise to resolve, inside render method of Route?
[英]Calling a method that has an await inside, does not wait for the promise to resolve
考慮這樣的場景:
function method1(): Promise<string> {
return new Promise((resolve, reject) => {
// do something
const response = true;
setTimeout(() => {
if (response) {
resolve("success");
} else {
reject("error");
}
}, 5000);
});
}
async function method2(): Promise<string> {
const result = await method1();
// do some other processing and return a different result
const result2 = result + "1";
return result2;
}
function method3(): void {
console.log("test 1");
const result = method2();
console.log("test 2");
}
method3();
我不確定為什么method2()
不會等待結果,因為它包含await
。 如果我在method3()
使用await
for method2()
調用,它會起作用:
async function method3(): Promise<string> {
console.log("test 1");
const result = await method2();
console.log("test 2");
}
即使在閱讀了如此多的博客文章、Mozilla 文檔和 stackoverflow 答案之后,我也無法真正理解 await/async 是如何工作的。
其中一條評論說“你無法逃避異步”。 並進一步解釋說,由於任何異步函數都會返回承諾,因此必須在函數階梯上await
它們。
希望有人可以為我澄清這一點。 謝謝你。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
每個異步函數都返回一個承諾,這將“向上鏈”直到第一次調用。
如果您真的需要,有一些庫旨在從 Promise 進行同步調用。
但問題是:這就是 javascript 的工作原理
async
then
語法 async function method1() { return new Promise((resolve, reject) => { setTimeout(() => resolve(1), 5000); }); } async function method2() { console.log("starting method 2"); const result = await method1(); console.log("finished method 2"); return result + 1 } async function method3() { console.log("starting method 3"); const result = await method2(); console.log("finished method 3"); return result + 1 } method3().then(result => console.log(result))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.