Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS Promises: Fulfill vs Resolve

I understand Promises to exist in one of three states: A Promise can either be pending (unresolved), fulfilled (resolved successfully) or rejected (resolved unsuccessfully).

Reading through the A+ Promise Spec and MDN's documentation, I am confused that they both acknowledge the fulfilled and rejected states but in the definition of the Promise constructor they specify two callbacks: resolve and reject. It seems we're using these two terms interchangeably; they are not.

Does not imply success:

re·solve /rəˈzälv/ verb
1. settle or find a solution to (a problem, dispute, or contentious matter).

Does imply success:

ful·fill /fo͝olˈfil/ verb
1. bring to completion or reality; achieve or realize (something desired, promised, or predicted).
2. carry out (a task, duty, or role) as required, pledged, or expected.

Why are we using resolve here when we're actually fulfilling the Promise? Is there an instance in which the value we pass to resolve might result in the Promise being rejected?

like image 595
rrowland Avatar asked Feb 14 '16 21:02

rrowland


People also ask

How do you resolve a fulfilled Promise?

Promise resolve() method: 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. The promise fulfilled with its value will be returned.

What happens if you don't resolve a Promise Javascript?

A promise is just an object with properties in Javascript. There's no magic to it. So failing to resolve or reject a promise just fails to ever change the state from "pending" to anything else. This doesn't cause any fundamental problem in Javascript because a promise is just a regular Javascript object.

What is a fulfilled Promise?

Definition of keep/fulfill one's promise : to do what one said one would definitely do.

Does Promise Return After resolve?

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.


3 Answers

Indeed, the resolve callback does not imply that the promise will be fulfilled.

The terms fulfilled, rejected, pending, settled, resolved and locked-in are defined in the EcmaScript2015 specs, 25.4 Promise Objects:

Any Promise object is in one of three mutually exclusive states: fulfilled, rejected, and pending:

  • A promise p is fulfilled if p.then(f, r) will immediately enqueue a Job to call the function f.

  • A promise p is rejected if p.then(f, r) will immediately enqueue a Job to call the function r.

  • A promise is pending if it is neither fulfilled nor rejected.

A promise is said to be settled if it is not pending, i.e. if it is either fulfilled or rejected.

A promise is resolved if it is settled or if it has been “locked in” to match the state of another promise. Attempting to resolve or reject a resolved promise has no effect. A promise is unresolved if it is not resolved. An unresolved promise is always in the pending state. A resolved promise may be pending, fulfilled or rejected.

A short overview, where I will use the term "autonomous" as the opposite of "locked in". They are the two possible values for a promise's dependency situation:

action dependency state resolved? settled?
new Promise((resolve, reject) => ...) autonomous pending no no
...resolve(thenable) locked-in pending* yes no
...resolve(other) autonomous fulfilled yes yes
...reject(any) autonomous rejected yes yes

* The thenable is now in control over the future state of our promise object.

The above quote mentions that a promise is locked-in to match the state "of another promise", but more precisely that "other promise" could also be a non-promise "thenable" as can be seen in the steps 11 and 12 of the process description in 25.4.1.3.2

  1. If IsCallable(thenAction) is false, then
          a. Return FulfillPromise(promise, resolution).
  2. Perform EnqueueJob ("PromiseJobs", PromiseResolveThenableJob, «‍promise, resolution, thenAction»)

A demo of resolve being called with a thenable, which in turn triggers a rejection:

const thenable = { // Could be a promise object, but does not have to be
    then(success, fail) {
        setTimeout(() => fail("gotcha!"), 1000);
    }
}

const p = new Promise((resolve, reject) => {
    console.log("1. The promise is created as pending");
    setTimeout(() => {
        resolve(thenable);
        console.log("2. It's resolved with a thenable; it's not yet settled");
    }, 1000);
});

p.catch(err => 
   console.log(`3. It's settled as rejected with error message "${err}"`)
);
like image 100
trincot Avatar answered Oct 06 '22 08:10

trincot


We can resolve a promise with another promise.

To answer your second question first: Yes, there is an instance in which the value we pass to resolve might result in the Promise being rejected, and that is if we pass it a rejected promise, e.g. Promise.reject().

To answer your first question of isn't resolve and fulfill the same: Consider the case where the value we pass to resolve is a pending promise. In this case our own promise will not settle immediately as a result:

a().then(() => new Promise(setTimeout)).catch(e => console.error(e));

In this case we say a promise is "resolved to" another promise, and it remains pending.

This is all happening behind our backs inside then, so it might be easier to look at a vintage case where a does not support promises (takes callbacks), and we don't flatten things correctly:

// Old times and unflattened for exposition:
new Promise((resolve, reject) => a(function(result) {
  resolve(new Promise(setTimeout));
}, reject))
.then(() => console.log("after setTimeout"))
.catch(e => console.error(e));

Here we see more clearly that resolve is called with another promise. Importantly, the resolved promise does not fulfill and fire the "after setTimeout" message until the second promise resolves (with a non-promise undefined value from setTimeout), at which point both promises become fulfilled (in other words: these two promises just formed a resolve chain).

This is key to understanding that resolved is different from fulfilled or even settled (fulfilled or rejected, not pending).

From States and Fates:

  • states: fulfilled, rejected, pending.
  • fates: resolved, unresolved.

The fate refers to whether the fate of a single promise has been reached, and does not correspond directly to any state transition, because of resolve chains.

like image 24
jib Avatar answered Oct 06 '22 10:10

jib


I think it's common to say that the Promise has resolved or settled. The resolution of the promise is the process in which the promise moves from the pending state and acquires a value associated to said state. So, if a promise is either fulfilled or rejected it will be a resolved promise (as it's resolution process has ended). If a promise enters the resolution process and never transitions into any other state it is said that the promise is unresolved (the resolution process never ended).

Regarding the other terms rejected or fulfilled, they are the other two states in which a pending promise can transition from. reject is pretty obvious IMO, it handles cases in which failure is supposed to happen. Now I do agree that fulfill can be somewhat ambiguous because it could simply mean that the promise has completed successfully (as in being resolved). It isn't supposed to describe the resolution process but the success (or the absence of error) of the task at hand.

The resolution process (to resolve a promise) can be observed in the A+ spec.

Edit.

The reason why people usually use resolve as the first argument name it's because the callback passed as the first argument invokes the resolution process. It doesn't fulfill the promise (the promise can still be rejected), it just starts resolving the promise. The reject mechanism isn't specified in the spec, it actually kind of short circuits the resolution process so that the promise is settled with reject (not actually resolved you see).

Here are some examples where p is rejected by using resolve:

This is point 2.3.1.

var p = new Promise(resolve => setTimeout(() => resolve(p), 0));

This is point 2.3.2.3.

var p = Promise.resolve(Promise.reject('reason'));

This is point 2.3.3.2.

var thenable = { get then() { throw new Error(); } }
var p = Promise.resolve(thenable);

This is point 2.3.3.3.3

var thenable = {
    then: function(resolvePromise, rejectPromise){
        rejectPromise(new Error());
    }
}
var p = Promise.resolve(thenable);

This is point 2.3.3.4.2

var thenable = {
    then: function(){
        throw new Error();
    }
}
var p = Promise.resolve(thenable);

I used Promise.resolve here instead of the first argument of the function passed down to the Promise constructor, but they should be the same. Many times the resolve function passed down to the constructor is:

var p = this;
var cb = function(x){
    resolve(p, x);
}

You can of course write down these tests as:

var p = new Promise(function(resolve){
    resolve(thenable);
});
like image 21
MinusFour Avatar answered Oct 06 '22 10:10

MinusFour