我有一个如下所示的数组,其中包含 itemId。我想循环遍历数组,并为每个 itemId 从 API 获取相应的数据,然后收集结果并渲染 DOM。无法让它工作......
gtinArray = [
"07314224054620",
"07314225267340",
"07313929649155",
"07314226417799",
"07314226224342"
]
getItem(gtin) {
return new Promise((resolve, reject) => {
const URL = "http://localhost:7071/api/GetItem?Gtin=" + gtin
fetch(URL)
.then(result => result.json())
.then(item => {
resolve(item)
})
})
}
pupulateCart() {
let itemRequests = []
gtinArray.forEach(gtin => {
itemRequests.push(getItem(gtin))
})
Promise.all(itemRequests)
.then(allItemData => {
console.log("All item data")
console.log(allItemData)
})
}
最佳答案
const gtinArray = ["1", "2", "3", "4", "5"]
function getItem(gtin) {
const URL = "https://jsonplaceholder.typicode.com/todos/" + gtin
return fetch(URL).then(response => response.json());
}
async function populateCart() {
let itemRequests = []
itemRequests = gtinArray.map(gtin => getItem(gtin));
return await Promise.all(itemRequests)
}
(async function () {
const data = await populateCart();
console.log(data);
})();
关于javascript - 循环遍历包含 itemId 的数组,从每个 itemid 的 api 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72218400/