Skip to content Skip to sidebar Skip to footer

Iterate Array And Wait For Promises

How can I iterate through an array of data using Promises and returning data? I have seen some promises.push(asyncFunc) methods but some of the entries from my array will fail so f

Solution 1:

If you need them to run in parallel, Promise.all is what you want:

functionstart(dbFiles) {
    returnPromise.all(dbFiles.map(getMp4));
}

That starts the getMp4 operation for all of the files and waits until they all complete, then resolves with an array of the results. (getMp4 will receive multiple arguments — the value, its index, and a a reference to the dbFiles arary — but since it only uses the first, that's fine.)

Usage:

start(filesFromDisk).then(function(results) {
    // `results` is an array of the results, in order
});

Just for completeness, if you needed them to run sequentially, you could use the reduce pattern:

functionstart(dbFiles) {
    return dbFiles.reduce(function(p, file) {
        return p.then(function(results) {
            returngetMp4(file).then(function(data) {
                results.push(data);
                return results;
            });
        });
    }, Promise.resolve([]));
}

Same usage. Note how we start with a promise resolved with [], then queue up a bunch of then handlers, each of which receives the array, does the getMp4 call, and when it gets the result pushes the result on the array and returns it; the final resolution value is the filled array.

Post a Comment for "Iterate Array And Wait For Promises"