'How to return value in sequential forEach loop?
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
})
Solution 1:[1]
Your forEachSequential doesn't really return anything. That's why you get undefined. When awaiting, you should attach a result to some variable, store it somewhere and then at the end of this function you should return it.
Now, you would like to return a tuple [string[], string[]]. To do so you have to create to arrays at the beginning of forEachSequential body, then call func in the loop and add a result to first array (let's say - success array) or second (failure array).
const successArray = [];
const failureArray = [];
for (let item of this) {
const result = await func(item);
if ('success' in result) {
successArray.push(result.success);
} else {
failureArray.push(result.error);
}
}
return [successArray, failureArray];
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Aitwar |
