Created
December 22, 2018 22:13
-
-
Save malipetek/c219e43294b1a89a2a67c444eaa5e208 to your computer and use it in GitHub Desktop.
sequentially do something and wait if there is a promise to wait
This file contains 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
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