Skip to content

Instantly share code, notes, and snippets.

@brianmriley
Created August 25, 2015 18:56
Show Gist options
  • Save brianmriley/530c4af072d43f31d4b4 to your computer and use it in GitHub Desktop.
Save brianmriley/530c4af072d43f31d4b4 to your computer and use it in GitHub Desktop.
var urlList = model.getURLs();
var loadAndParse = function (url)
{
// both load() and parse() are promise based functions
return load(url).then(parse);
};
/**
* Allows for the sequentially calling of promise based functions by iterating over a list of
* items and then calling the next promise based function when the previous one has resolved.
*
* @param {array} arr List of values or objects used to pass into the promise-based `iterator`
* parameter function.
* @param {function} iterator The promise-based function to call with an item from the `arr` parameter.
* @returns {promise}
*/
var promiseLoopSequence = function (arr, iterator)
{
// create a empty promise to start our series (so we can use `then`)
// we save Q to qPromise so JSLint doesn't complain about no "new" keyword
var qPromise = Q;
var currentPromise = qPromise();
var promises = arr.map(function (el)
{
return currentPromise = currentPromise.then(function ()
{
// execute the next function after the previous has resolved successfully
return iterator(el);
});
});
// group the results and return the group promise
return Q.all(promises);
};
return promiseLoopSequence(urlList, loadAndParse);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment