Skip to content

Instantly share code, notes, and snippets.

@malipetek
Created December 22, 2018 22:13
Show Gist options
  • Save malipetek/c219e43294b1a89a2a67c444eaa5e208 to your computer and use it in GitHub Desktop.
Save malipetek/c219e43294b1a89a2a67c444eaa5e208 to your computer and use it in GitHub Desktop.
sequentially do something and wait if there is a promise to wait
Array.prototype.oneByOne = function(action){
var arr = this;
return new Promise(function(resolve, reject){
var results = [];
var act = function (i) {
// action expexted to return a promise but otherwise should still work
var actionResult = action.call(arr[i], arr[i], i);
if(!actionResult || actionResult.constructor != Promise){
actionResult = new Promise(function (res, rej){
res(actionResult);
});
}
actionResult.then(function (resultOfSomething) {
results.push(resultOfSomething);
if(++i < arr.length) {
act(i);
}else{
resolve(results);
}
}).catch(function(err) {throw new Error(err)});
}
act(0);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment