This is how I'm using a sequential forEach loop to handle some file uploads. Now I want to get a total result for each upload: For each file I resolve with an object (success or error). At the end I want to get a returned array to display the result (File 1 successful, file 2 error and so on).
But with this code I only get undefined for the last output. What am I missing?
Maybe it would even be better to return two string arrays: one successful and one failed array with filenames.
Array.prototype.forEachSequential = async function (
func: (item: any) => Promise<void>
): Promise<void> {
for (let item of this) await func(item)
}
async uploadFiles(files: [File]): Promise<any> {
const result = await files.forEachSequential(
async (file): Promise<any> => {
const res = await new Promise(async (resolve, reject) => {
// do some stuff
resolve({ success: file.filename })
// or maybe
resolve({ error: file.filename })
})
console.log(res) // returns object as expected
return res
}
)
// Get all results after running forEachSequential
console.log('result', result) // result: undefined
})
forEachSequentialdoes not return anything, it only "consumes" all promises. You want to build up an array and put the results there...returnis missing...