Created
December 10, 2014 03:00
-
-
Save alandotcom/809dc1979d0c69342d09 to your computer and use it in GitHub Desktop.
Async promise loop
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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