Skip to content

Instantly share code, notes, and snippets.

@helsont
Created August 11, 2016 20:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save helsont/b1153a7ea99ca71c98d4079c885b38a4 to your computer and use it in GitHub Desktop.
Save helsont/b1153a7ea99ca71c98d4079c885b38a4 to your computer and use it in GitHub Desktop.
Utility to in order iterate through an array of promises and return an array of results after completion.
'use strict';
/**
* Sync promise
*
* Utility to in order iterate through an array of promises and return
* an array of results after completion.
*
* Usage:
*
* syncPromise([1, 2, 3, 4], (item, idx, array) => {
* // process
* })
* .then((results) => {
*
* })
*
* Iterator params
* @param {Any} item The current value in the array
* @param {Number} idx The index of the iterator
* @param {Array} array The original array you provided
* @return {Promise} A promise which returns an array of resolve promises
* or an error on failure.
*/
const next = (idx, array, forEach, aggregate, promise) => {
let item = array[idx];
let result;
// Catch errors and reject on failure
try {
result = forEach(item, idx, array);
} catch (error) {
return promise.reject(error);
}
// Wrap result in promise
if (!(result instanceof Promise)) {
result = Promise.resolve(result);
}
// Attempt promise execution
return result.then((value) => {
// Append result to array to later return
aggregate.push(value);
// Perform next iteration
if (idx < array.length - 1) {
return next(idx + 1, array, forEach, aggregate, promise);
}
// Resolve and return the array of all results
return promise.resolve(aggregate);
});
};
const syncPromise = (array, forEach) => {
let aggregate = [];
return new Promise((resolve, reject) => {
next(0, array, forEach, aggregate, { resolve, reject });
});
};
module.exports = syncPromise;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment