The question is the title. I'm trying to get a deeper understanding of promises and I think I've figured out how Promise.resolve(thenable)
works, or at least mostly how it works, looking at the examples on MDN. I'm wondering if there's a difference between the two. I whipped up this example to show them behaving the same, in way that I would think would show differences in behaviour if there was going to be any. But obviously this test alone isn't good enough to conclude there's nothing different about them, so I've come here.
let thenable = {
then(resolve) {
setTimeout(()=>{
resolve((()=>{
console.log('test');
return thenable;
})());
}, 1000);
},
};
let p1 = Promise.resolve(thenable);
let p2 = new Promise(thenable.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.
Promise.all() will reject immediately upon any of the input promises rejecting. In comparison, the promise returned by Promise.allSettled() will wait for all input promises to complete, regardless of whether or not one rejects. Use allSettled() if you need the final result of every promise in the input iterable.
resolve(value) — if the job is finished successfully, with result value . reject(error) — if an error has occurred, error is the error object.
It is not safe to resolve/reject promise multiple times. It is basically a bug, that is hard to catch, becasue it can be not always reproducible.
In your example, the two work mostly the same. You're right, passing resolve
and reject
to the then
method invocation of a thenable is what basically happens when you are resolving a promise with the thenable object.
However, there are a few differences:
then
method of a thenable is called as a method on (with the this
context as) the thenable object, unlike your new Promise(thenable.then)
does - a .bind(thenable)
would fix that.Promise.resolve
(obviously) has to check first whether the passed object is a thenable at all, it also handles obscure cases where accessing (not calling) .then
throwsa subtle discrepance in timing: Promise.resolve
schedules even the then
call asynchronously:
Promise.resolve({
get then() {
console.log("property access");
return function(res, rej) {
console.log("method call");
res("fulfillment");
};
}
}).then(console.log);
console.log("sync execution end");
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