以下是我要执行的操作的摘要:
如何访问已解决的项目?
以下是数据调用的简化版本:
// First api call to retrieve ReportDates:
fetch(baseUrl + "api/Woh/Summary/" + accountId):
AccountId.Items: [
{
AccountId: 124,
clientName: XYZ,
reportDate: "2018-09-30"
},
{
AccountId: 124,
clientName: XYZ,
reportDate: "2018-09-20"
},
]
// Next using a loop to make fetch calls using reportDates:
fetch(baseUrl + "api/Woh/Details/" + accountId + "/" + reportDate)
reportDate.Items(first loop):
[
{a:y},
{b:z},
{c:v}
]
reportDate.Items(second loop):
[
{a:y},
{b:z}
]
现在,我正在尝试将每个调用中的所有项目都推送到一个数组中。这就是循环完成后我无法访问的地方。
这是我的代码:
const getProjectsData = async () => {
let projectsData = await fetch(baseUrl + "api/Woh/Summary/" + accountId);
let projectsJson = await projectsData.json();
let reportDates = projectsJson.Items.map(item => formatDate(item.ReportDate));
let projects = [];
reportDates.forEach(reportDate => {
fetch(baseUrl + "api/Woh/Details/" + accountId + "/" + reportDate)
.then(res => res.json())
.then(data => {
data.Items.forEach(item => projects.push(item));
})
});
console.log(dates);
// console logging dates shows the array of items that I want, but when I try to access them individually with dates[0], it shows as undefined.
}
答案 0 :(得分:0)
如果您使用async/await
,则不必对循环进行过多思考。您可以使用for块进行遍历,如下所示:
async function getResults(objs) {
const responses = [];
for (let obj of objs) {
const response = await fetch(`/data/${obj.id}`);
const json = await response.json();
responses.push(json);
}
return responses;
}
getResults([{id:1},{id:2}])