Last active
November 4, 2016 15:28
-
-
Save davidsharp/9a6ebbb1b716321360adfa6ce56a52f4 to your computer and use it in GitHub Desktop.
promiseFor(), tidies up the messy nature of Promises with for-loops
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
//promiseFor creates 'n' promises, and returns them as a promise | |
// This only resolves if all the promises resolve | |
// It takes an integer and a Promise-like function | |
// The promise-like function should take 3 arguments: | |
// - An integer, representing an index | |
// or a number meaningful to your function | |
// - The standard Promise resolve function | |
// - The standard Promise reject function | |
function promiseFor(forCount,promiseFn){ | |
//return a promise | |
return new Promise(function(res,rej){ | |
var a=[]; | |
for(var i=0;i<forCount;i++){ | |
//create all our inner promises | |
a.push(new Promise( | |
function(res,rej){ | |
promiseFn.call(null,i,res,rej); | |
} | |
)); | |
} | |
Promise.all(a).then(res,rej); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In retrospect, I feel like this is dumb.
You're probably better off mapping an array and wrapping it in a
Promise.all
. It might mean building lots of new functions, rather than calling a single function, if not handled quite right, but it means you're not depending on just an index in your Promise-like function.The intention would certainly be clearer, at least.