Say I have two functions:
function f1() {
return new Promise<any>((resolve, reject) => {
resolve(true);
});
}
function f2() {
}
How do I know if f1
will return Promise
and f2
will not?
all() returns a new promise that immediately rejects with the same error. Also, the Promise. all() doesn't care other input promises, whether they will resolve or reject. In practice, the Promise.
resolve() method in JS returns a Promise object that is resolved with a given value. Any of the three things can happened: If the value is a promise then promise is returned. If the value has a “then” attached to the promise, then the returned promise will follow that “then” to till the final state.
Promises are used to handle asynchronous operations in JavaScript. They are easy to manage when dealing with multiple asynchronous operations where callbacks can create callback hell leading to unmanageable code.
Returns a new Promise object that is resolved with the given value. If the value is a thenable (i.e. has a then method), the returned promise will "follow" that thenable, adopting its eventual state; otherwise, the returned promise will be fulfilled with the value.
So it's just about normalizing the output. Then run it through Promise.resolve()
and co.
var possiblePromise = f1();
var certainPromise = Promise.resolve(possiblePromise).then(...);
or
var possiblePromises = [f1(), f2()];
Promise.all(possiblePromises).then(values => ...);
But you need to have a basic Idea of what these functions return. For Example: Both examples would fail with
function f3(){
return [somePromise, someOtherPromise];
}
var arrayOfPromisesOrValues = f3();
//here you'll still deal with an Array of Promises in then();
Promise.resolve(arrayOfPromisesOrValues).then(console.log);
//neither does this one recognize the nested Promises
Promise.all([ f1(), f2(), f3() ]).then(console.log);
//only these will do:
Promise.all(f3()).then(console.log);
Promise.all([ f1(), f2(), Promise.all(f3()) ]).then(console.log);
You need to know that f3
returns an Array of Promises or values and deal with it. Like you need to know that f1
and f2
return a value or a Promise of a value.
Bottom line: you need to have a basic knowledge of what a function returns to be able to run the result through the proper function to resolve the promises.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With