這個問題在這里已經有了答案: 如何從異步呼叫回傳回應 (42 個回答) 4 天前關閉。
我不確定為什么 await 對我不起作用,有人可以幫助我嗎?我遵循了一些指南并完全相同地復制了它,但仍然無法正常作業。我需要在呼叫 console.log(CardsID.length) 之前填充 CardsID 陣列
代碼:
"[LL_REPTAG_URLPREFIXFULL /]/api/v2/businessworkspaces?where_workspace_type_id=54";
async function postData() {
let response = await fetch(url, {
method: "GET", // *GET, POST, PUT, DELETE, etc.
headers: {
"Content-Type": "application/json",
OTCSTicket: "[LL_REPTAG_OTCSTICKET /]",
},
//body: JSON.stringify(data) // body data type must match "Content-Type" header
});
return await response.json();
}
//(async function(){
postData().then(function (data) {
// Log the data to the console
// You would do something with both sets of data here
//console.log(data);
data.results.forEach((element) => {
CardsID.push(element.data.properties.id);
console.log("added");
});
});
//})();
console.log(CardsID.length);
console.log(CardsID);```
result (console):
0
[]
[]
[]
24 added
uj5u.com熱心網友回復:
您在 postData() 呼叫之后立即呼叫 console.logs,這是異步的(好吧,承諾),因此不會等待執行完成。您需要將 console.logs 放在 then 處理程式中,如下所示:
postData().then(function (data) {
data.results.forEach((element) => {
CardsID.push(element.data.properties.id);
console.log("added");
});
console.log(CardsID.length);
console.log(CardsID);
});
或者(為了一致性),您可以將其全部設為異步/等待,例如:
async function postData() {
const response = await fetch(url, {
method: "GET", // *GET, POST, PUT, DELETE, etc.
headers: {
"Content-Type": "application/json",
OTCSTicket: "[LL_REPTAG_OTCSTICKET /]",
},
});
return await response.json();
}
async function run() {
const data = await postData();
const CardsID = [];
for (const element of data.results) {
CardID.push(element.data.properties.id);
console.log("added");
}
console.log(CardsID.length);
console.log(CardsID);
}
run();
uj5u.com熱心網友回復:
問題是postData().then在承諾得到解決后,塊中的代碼是異步執行的。該console.log(CardsID.length)陳述句將在then塊執行之前運行。
要解決這個問題,您可以console.log在 promise 回呼中運行該陳述句。
postData().then(function (data) {
data.results.forEach((element) => {
CardsID.push(element.data.properties.id);
console.log("added");
});
// move the console.log statement here
console.log(CardsID.length);
console.log(CardsID);
});
uj5u.com熱心網友回復:
請記住,.then 塊下方的代碼將在決議之前運行,因為 Javascript 等待決議,但會繼續通過其同步運行來執行任何異步代碼下方的代碼。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/338077.html
標籤:javascript 阿贾克斯 异步 异步等待
