Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
[Javascript] Queue Asynchronous Function using Promise
var Promise = require('es6-promise').Promise;
var funcs = [];
funcs[0] = function (cb) {
setTimeout(function () {
console.log(1);
cb();
}, 2000);
};
funcs[1] = function (cb) {
setTimeout(function () {
console.log(2);
cb();
}, 500);
};
funcs[2] = function (cb) {
setTimeout(function () {
console.log(3);
cb();
}, 2000);
};
execSteps(funcs); //result: 1 2 3 Quere is over
function execSteps(funcs) {
funcs.reverse();
var promises = [];
//recursive function
var execCore = function (n) {
promises[n] = new Promise(function (resolve, reject) {
funcs[n](function () {
resolve();
});
});
promises[n].then(function () {
if (funcs[n - 1]) {
execCore(n - 1);
} else {
console.log('Quere is over');
}
});
};
execCore(funcs.length - 1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.