我試圖隱藏一些進行計算的代碼的延遲。
下面的例子。在下面的第一種情況下,我得到了預期的答案:
async function calculateStuff(thing) {
//do stuff here
return {"a": a, "b": b, "c": c};
}
const data = await calculateStuff(obj); //takes a while
const first = data["a"] //valid data
const second = data["b"] //valid data
const third = data["c"] //valid data
我想通過執行以下任一操作來隱藏 calculateStuff 的延遲,但是這兩種方法都使我的變數變為未定義:
async function calculateStuff(thing) {
//do stuff here
return {"a": a, "b": b, "c": c};
}
data = calculateStuff(obj); //takes a while
//...other calculations here...
await data;
const first = data["a"] //undefined
const second = data["b"] //undefined
const third = data["c"] //undefined
同樣地:
async function calculateStuff(thing) {
//do stuff here
return {"a": a, "b": b, "c": c};
}
data = calculateStuff(obj); //takes a while
//...other calculations here...
const first = await data["a"] //undefined
const second = await data["b"] //undefined
const third = await data["c"] //undefined
我究竟做錯了什么?
uj5u.com熱心網友回復:
異步函式將回傳一個 Promise。呼叫await myAsyncFunction(), 將在 Promise 完成后回傳Promise 的值。請注意return上一條陳述句中的 。它不會改變指標到位。
例如呼叫await data不會改變data。
您可以通過呼叫獲得您期望的輸出data = await data。
async function test()
{
return {a: 1, b: 2};
}
async function run()
{
let data = test();
data = await data;
console.log("A", data.a);
}
run();
您也可以使用.then().
async function test()
{
return {a: 1, b: 2};
}
async function run()
{
let data = test();
data.then((out) => {
console.log("A", out.a);
});
}
run();
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/403078.html
標籤:
