I have an array of questions.
Each question has some answers which are some files to upload.
Everything goes well instead of the fact that the API call is not waiting for Promise.all to finish.
Here are the steps:
map through questions array, if a question is
image
type, then get all the files and try to upload them.after upload resolve all the promises from upload and add an answer to that question the result of
Promise.all();
After the loop through all the questions is ready, make an API call to save into DB which now is not waiting to upload all the files and resolve everything in that array.
export function sendReview (taskId, companyId, questions, navigation) {
return async (dispatch) => {
dispatch(actions.sendReview.pending());
try {
let user = await getUser();
user = JSON.parse(user);
questions.map(async question => {
if (question.type === 'image') {
let images = question.answer;
if (images.length > 0) {
const results = images.map(async image => {
return await imageApi.upload(image).then(res => {
return res.url;
});
});
question.answer = await Promise.all(results).then(completed => {
return completed;
});
}
}
});
const data = await tasksApi.sendReview({
task_id: taskId,
company_id: companyId,
user_id: user.id,
questions: JSON.stringify(questions)
});
if (data.status === 201) {
markAsCompleted(taskId);
navigation.navigate('MyTasks');
dispatch(actions.sendReview.success({}));
}
else {
dispatch(actions.sendReview.error());
}
} catch (err) {
dispatch(actions.sendReview.error(err));
}
};
}
Here is the function used.
How can I make sure that all the items in .map()
are ready and just after that make API call?