我嘗試使用此解決方案通過異步等待從多個 api 獲取資料,但輸出未定義,可能出了什么問題?
const getData = async (jwt) => {
try {
const [response1, response2, response3] = await Promise.all(
[
fetch("http://localhost:3000/api/confirmed"),
fetch("http://localhost:3000/api/deaths"),
fetch("http://localhost:3000/api/recovered"),
],
{
method: "GET",
headers: {
"user-agent": "vscode-restclient",
"content-type": "application/json",
accept: "application/json",
authorization:
"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwibmFtZSI6IkxlYW5uZSBHcmFoYW0iLCJ1c2VybmFtZSI6IkJyZXQiLCJpYXQiOjE1OTY1MDY4OTN9.KDSlP9ALDLvyy0Jfz52x8NePUejWOV_mZS6cq4-JZXs",
},
}
);
const { data1 } = await response1.json();
const { data2 } = await response2.json();
const { data3 } = await response3.json();
console.log(data1, data2, data3);
} catch (err) {
console.error(`Error: ${err}`);
}
};
getData();
uj5u.com熱心網友回復:
Promise.all只接受一個引數,一個promise陣列。因此,您的第二個引數(帶有methodand的物件headers)將被忽略。該物件需要作為第二個引數傳遞給fetch函式,而不是Promise.all.
嘗試以下操作:
const getData = async (jwt) => {
try {
const fetchOptions = {
method: "GET",
headers: {
"user-agent": "vscode-restclient",
"content-type": "application/json",
accept: "application/json",
authorization:
"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwibmFtZSI6IkxlYW5uZSBHcmFoYW0iLCJ1c2VybmFtZSI6IkJyZXQiLCJpYXQiOjE1OTY1MDY4OTN9.KDSlP9ALDLvyy0Jfz52x8NePUejWOV_mZS6cq4-JZXs",
},
};
const [response1, response2, response3] = await Promise.all(
[
fetch("http://localhost:3000/api/confirmed", fetchOptions),
fetch("http://localhost:3000/api/deaths", fetchOptions),
fetch("http://localhost:3000/api/recovered", fetchOptions),
],
);
const { data1 } = await response1.json();
const { data2 } = await response2.json();
const { data3 } = await response3.json();
console.log(data1, data2, data3);
} catch (err) {
console.error(`Error: ${err}`);
}
};
getData();
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/438455.html
標籤:javascript api 异步等待 拿来
下一篇:從快取中獲取訊息
