The ES6 Promise specification contains the very useful constructor for creating a promise, like so:
var promise = new Promise(function(resolve, reject){
resolve("hi");
});
promise.then(function(message){
console.log(message);
});
But often you need to create a promise several times, with slightly different parameters, and this ends up as a small wrapper function around the Promise
constructor:
function greet(name){
return new Promise(function(resolve, reject){
resolve("hi "+name);
});
}
greet("Pete").then(function(message){
console.log(message);
});
It would therefore be useful if this was built into the Promise
object as a factory, so you could instead do:
var greet = Promise.factory(function(name, resolve, reject){
resolve("hi "+name);
});
greet("Pete").then(function(message){
console.log(message);
});
The factory takes any number of parameters and adds the promise callbacks (resolve
and reject
) to the end of the argument list. It can be defined like this:
Promise.factory = function(factory){
return function(...args){
return new Promise(function(...cbs){
return factory(...args, ...cbs);
});
}
}
This can be used for, for example, ajax:
var getData = Promise.factory(function(params, resolve, reject){
$.getJSON("/path/to/endpoint", params, function(data){
resolve(data);
});
});
Promise.all([
getData({key: "value1"}),
getData({key: "value2"}),
getData({key: "value3"})
]).then(function(result){
console.log(result[0], result[1], result[2]);
});