Skip to content

Instantly share code, notes, and snippets.

@alandotcom
Created December 10, 2014 03:00
Show Gist options
  • Select an option

  • Save alandotcom/809dc1979d0c69342d09 to your computer and use it in GitHub Desktop.

Select an option

Save alandotcom/809dc1979d0c69342d09 to your computer and use it in GitHub Desktop.
Async promise loop
var Promise = require('bluebird');
var _ = require('lodash');
function promiseA() {
return Promise.resolve([1]);
}
function promiseB(prevResult) {
prevResult.push(2)
return Promise.resolve(prevResult);
}
function promiseC(prevResult) {
prevResult.push(3)
return Promise.resolve(prevResult);
}
function loopingPromise(prevResult) {
var nextResult = prevResult;
if (nextResult.length === 10) {
return Promise.resolve(nextResult);
}
return new Promise(function(resolve, reject) {
setTimeout(function() {
nextResult.push(_.last(nextResult) + 1);
resolve(nextResult);
}, 10);
}).then(loopingPromise);
};
promiseA()
.then(promiseB)
.then(promiseC)
.then(loopingPromise)
.then(function (result) {
console.log(result);
})
.catch(function(err) {
console.log('ERROR: ', err);
});
/*
» node promiseloop.js
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment