Im have a request loop what send a image or multiple images at a promise and resolve returning "true" boolean value ¿the problem? the promise is resolved before ends of loop and the request is like "background" my question is "How to await the end of loop for to resolve the promise"? im try using async await at promise but does not working
export const sendQuestionArray = (questionArr) => {
return new Promise( async(resolve, reject) => {
await questionArr.map((question) => {
const formSend = new FormData()
formSend.append('idAsignacion', question.question_id)
formSend.append('pregunta', question.question)
formSend.append('respuesta', question.value ? 'CUMPLE' : 'NO_CUMPLE')
formSend.append('imagenes', JSON.stringify(question.photo))
formSend.append('comments', question.comments)
globalApi.post('/api-agv/audit/set_answer_audit', formSend)
})
resolve(true)
})
}
Thanks for the asks
You can await till POST request ends on each iteration (for each question).
Make sure your globalApi.post returns Promise<any>.
export const sendQuestionArray = async questionArr => {
for (const question of questionArr) {
const formSend = new FormData()
formSend.append('idAsignacion', question.question_id)
formSend.append('pregunta', question.question)
formSend.append('respuesta', question.value ? 'CUMPLE' : 'NO_CUMPLE')
formSend.append('imagenes', JSON.stringify(question.photo))
formSend.append('comments', question.comments)
await globalApi.post('/api-agv/audit/set_answer_audit', formSend) // If 'post' method returns Promise
}
return true // will happen only after all requests
}
By the way: you don't need to use Promise constructor and async/await at the same time, async method always returns promises.
If you need to wait till all requests ends, just call sendQuestionArray with await keyword:
// elsewhere in code
const result = await sendQuestionArray(questionArr)
console.log(result) // 'true', printed only after request sequence