Last active
September 5, 2021 14:00
-
-
Save tangzhen/7b9434df8beac308fd3e to your computer and use it in GitHub Desktop.
javascript promise while 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
'use strict'; | |
// ref: http://blog.victorquinn.com/javascript-promise-while-loop | |
var q = require('bluebird'); | |
var promiseWhile = function (condition, action) { | |
var resolver = q.defer(); | |
var loop = function () { | |
if (!condition()) { | |
return resolver.resolve(); | |
} | |
return q.cast(action()) | |
.then(loop) | |
.catch(resolver.reject); | |
}; | |
process.nextTick(loop); | |
return resolver.promise; | |
}; | |
// And below is a sample usage of this promiseWhile function | |
var sum = 0, | |
stop = 10; | |
promiseWhile(function () { | |
// Condition for stopping | |
return sum < stop; | |
}, function () { | |
var deffered = q.pending(); | |
setTimeout(function () { | |
sum++; | |
// Print out the sum thus far to show progress | |
console.log(sum); | |
deffered.resolve(); | |
}, 250); | |
return deffered.promise; | |
}).then(function () { | |
// Notice we can chain it because it's a Promise, | |
// this will run after completion of the promiseWhile Promise! | |
console.log("Done"); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment