JS Promises: Fulfill vs Resolve

前端 未结 4 901
我寻月下人不归
我寻月下人不归 2020-12-31 08:07

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

相关标签:
4条回答
  • 2020-12-31 08:43

    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()       | 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}"`)
    );

    0 讨论(0)
  • 2020-12-31 08:48

    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);
    });
    
    0 讨论(0)
  • 2020-12-31 09:03

    A resolved Promise having a value of an Error does not automatically convert the Promise to rejected Promise

    var p = Promise.resolve(new Error("rejected"));
    p.then(function(data) {
      console.log(data, p)
    })


    See also States and fates


    If you could include information on how resolve might be used to reject the Promise rather than fulfill it, I would consider this a complete answer.

    Not certain about reason for or expected result of using resolve to reject a Promise ? Though simplest approach to achieve this would be to pass reject as a parameter when resolve called Promise.resolve(Promise.reject(/* Error here */))

    var _reject = function(err) {
      return Promise.reject(err)
    }
    
    var resolver = function(resolve, reject) {  
        return resolve(_reject(new Error("reject within resolve")))
    }
    
    var p = new Promise(resolver);
    
    p.then(function(data) {
      console.log("resolved", data)
    },function(data) {
      console.log("rejected:", data, "promise:", p)
    })

    If expected result is to catch errors or a rejected Promise passed to resolve where handlers may be attached, while maintaining the "resolved" PromiseStatus , could use unhandledrejection event , Promise.reject directly or at chrome / chromium 49+ could use PromiseRejectionEvent

    window.addEventListener("unhandledrejection", function(event) {
      // handle unhandled rejected `Promise`
      console.log("unhandledrejection:", event.reason, event.promise);
    });
    
    Promise.resolve(new PromiseRejectionEvent("Error", {
        // unhandled `rejected` `Promise` 
        promise: Promise.reject(new Error("custom rejection")),
        reason: "custom rejection"
      }))
      .then(function(data) {
        // `PromiseRejectionEvent` contains a `rejected`
        // `Promise` , which triggers `"unhandledrejection"` event
        // to handle rejected `Promise` here, resolve `.promise` 
        // object of `PromiseRejectionEvent`
        console.log("resolved:", data);
      }, function(err) {
        console.log("rejected", err)
    })

    could also throw an Error within Promise constructor without using resolve or reject , which should be handled by onRejected or catch

    new Promise(function(resolve, reject) {
      throw new Error("reject within Promise constructor")
    })
    // catch here handles `Error` from `Promise` constructor
    // will be `resolved` at `.then()` if `Error` not `throw`n to `.then()` 
    // .catch(function(e) {
    //  console.log("caught error:", e);
      /* return e : pass `e` to `.then()` as `resolved` `Promise` */
      /* throw e : pass `e` to `.then()` as `rejected` `Promise`  */
    //})
    
    .then(function(data) {
      console.log("resolved:", data)
    }, function(err) {
      console.log("rejected:", err);
      throw err
    })
    .catch(function(e) {
      console.log("caught error:", e);
      /* return e : pass `e` to `.then()` as `resolved` `Promise` */
      /* throw e : pass `e` to `.then()` as `rejected` `Promise`  */
    })


    Explanation: There are a number of approaches to handling both resolved and rejected Promise objects , depending on application and expected results.

    0 讨论(0)
  • 2020-12-31 09:07

    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.

    0 讨论(0)
提交回复
热议问题