Creating a (ES6) promise without starting to resolve it
I want to add my 2 cents here. Considering exactly the question "Creating a es6 Promise without starting resolve it" I solved it creating a wrapper function and calling the wrapper function instead. Code:
Let's say we have a function f
which returns a Promise
/** @return Promise<any> */
function f(args) {
return new Promise(....)
}
// calling f()
f('hello', 42).then((response) => { ... })
Now, I want to prepare a call to f('hello', 42)
without actually solving it:
const task = () => f('hello', 42) // not calling it actually
// later
task().then((response) => { ... })
Hope this will help someone :)
Referencing Promise.all()
as asked in the comments (and answered by @Joe Frambach), if I want to prepare a call to f1('super')
& f2('rainbow')
, 2 functions that return promises
const f1 = args => new Promise( ... )
const f2 = args => new Promise( ... )
const tasks = [
() => f1('super'),
() => f2('rainbow')
]
// later
Promise.all(tasks.map(t => t()))
.then(resolvedValues => { ... })
Good question!
The resolver passed to the promise constructor intentionally runs synchronous in order to support this use case:
var deferreds = [];
var p = new Promise(function(resolve, reject){
deferreds.push({resolve: resolve, reject: reject});
});
Then, at some later point in time:
deferreds[0].resolve("Hello"); // resolve the promise with "Hello"
The reason the promise constructor is given is that:
- Typically (but not always) resolution logic is bound to the creation.
- The promise constructor is throw safe and converts exceptions to rejections.
Sometimes it doesn't fit and for that it the resolver runs synchronously. Here is related reading on the topic.