Skip to content

Instantly share code, notes, and snippets.

@davidsharp
Last active November 4, 2016 15:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidsharp/9a6ebbb1b716321360adfa6ce56a52f4 to your computer and use it in GitHub Desktop.
Save davidsharp/9a6ebbb1b716321360adfa6ce56a52f4 to your computer and use it in GitHub Desktop.
promiseFor(), tidies up the messy nature of Promises with for-loops
//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);
});
}
@davidsharp
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment