I want to make multiple calls for which I have to wait for the answer, and afterwards I want to group all responses in an array. I've not succeeded to do this.
The res
constant in code below still retains the array of promises, not their results. I have no idea what else to try. No other stackoverflow answers have been helpful.
What I've tried:
const getProjectData = async (projectID) => await callAPI(`/projects/${projectID}`);
const solve = async () => {
const projects = [];
currentUserProjectIDs.forEach((project) => {
projects.push(getProjectData(project));
});
console.log("projects", projects);
const res = await Promise.all(projects);
console.log("solve res", res);
return res;
};
const res = await solve();
console.log("res", res);
Below is the result of the last console log:
res [
Response {
size: 0,
timeout: 0,
[Symbol(Body internals)]: { body: [PassThrough], disturbed: false, error: null },
[Symbol(Response internals)]: {
url: 'http://localhost:4000/projects/1',
status: 200,
statusText: 'OK',
headers: [Headers],
counter: 0
}
},
Response {
size: 0,
timeout: 0,
[Symbol(Body internals)]: { body: [PassThrough], disturbed: false, error: null },
[Symbol(Response internals)]: {
url: 'http://localhost:4000/projects/4',
status: 200,
statusText: 'OK',
headers: [Headers],
counter: 0
}
}
]
callAPI
function:
export const callAPI = async (path, body, method = "GET") => {
const config = {
method: method,
headers: {
"Content-Type": "application/json",
},
};
if (body) {
config.body = JSON.stringify(body);
}
const URL = `${process.env.HOST}${path}`;
return await fetch(URL, config);
};
EDIT:
I have tried another way, but still unsuccessful. In the code below, the console.log inside the second .then()
logs the correct data, but the returned prj
is still an empty array...
const solve = async () => {
const projects = [];
currentUserProjectIDs.map((p) => {
callAPI(`/projects/${p}`)
.then((r) => {
return r.json();
})
.then((a) => {
console.log("a", a);
projects.push(a);
return a;
});
});
return projects;
};
const prj = await solve();
console.log("prj", prj);