We can call Promise.resolve(value)
as well as Promise.resolve(promise)
. I can understand where and how I should use the first call but am not sure about the second one.
Why not simply use the promise as argument in the first place? I mean calling:
promise1.then()
instead of:
Promise.resolve(promise1).then()
?
The Promise.resolve() method "resolves" a given value to a Promise . If the value is a promise, that promise is returned; if the value is a thenable, Promise.resolve() will call the then() method with two callbacks it prepared; otherwise the returned promise will be fulfilled with the value.
In TypeScript, promise type takes an inner function, which further accepts resolve and rejects as parameters. Promise accepts a callback function as parameters, and in turn, the callback function accepts two other parameters, resolve and reject. If the condition is true, then resolve is returned; else, returns reject.
Promises in Angular provide an easy way to execute asynchronous functions that use callbacks, while emitting and completing (resolving or rejecting) one value at a time. When using an Angular Promise, you are enabled to emit a single event from the API.
"The point is that a promise will never resolve to another promise. It will always resolve to that promise's (eventual) value." Is jQuery $.
Promise.resolve
is basically "I don't care what this is, give me a promise". Generally, whenever you get an argument that might be a promise Promise.resolve
is the correct way to work with it (vs. detecting it's a promise clunkily).
It's useful for:
It's also implicitly called a lot with promises.
Promise.all
or Promise.race
- it implicitly Promise.resolve
s all values.Promise#then(...)
it will call Promise.resolve
on it.await
a value Promise.resolve
is implicitly called on it.And so on.
If you have a value that might be a Promise, Promise.resolve
is great.
In the program that I am working on now, I have a lot of places were I create a UI component with callbacks to handle various inputs. Some times, those callbacks need to return promises, sometimes they don't. Rather than put the onus on the callback, I always wrap the return value in Promise.resolve
and boom, problem solved.
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