为什么async request with 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

您正在呼叫控制台。在postData()调用之后立即记录日志,这是异步的(好吧,promise),因此不会等待执行完成。要么您需要放置控制台。然后处理程序中的日志,如下所示:

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/await,例如:

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

问题是postData().then块中的代码是异步执行的,在承诺得到解决后。console.log(CardsID.length)语句将在then块执行之前运行。

要解决这个问题,您可以在promise回调中运行console.log语句。

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

请记住,.then块下面的代码将在解析之前运行,因为Javascript会等待解析,但会继续同步运行以执行任何异步代码下面的代码。

最新更新