简体   繁体   中英

promise Q not working consistently

Im using the Q library of promise and I've some basic question I've created this code and when I omit the first return Q word I got error (return Q(100)),but for the second and the third there is no problem if I omit them, the code is still working,why?

  function firstFn() {
        return Q(100);
    };


    function secFn(){
        return Q(200);
    };

    function thirdFn(){
        return q(300);
    };


    firstFn().then(function(a){
        alert(a);
        return secFn();
    }).then(function(b){
        alert(b);
        return thirdFn();
    }).then(function(c){
        alert(c)
    });

You are invoking .then(function(a)...) on the value returned from firstFn so it needs to return something that has a .then function on it.

For the the other 2 functions, you are invoking them within a Q .then() callback. If you return a promise from those callbacks, Q will take advantage of them but if you don't return anything, Q is ok with that too.

To elaborate on what Robert Levy has said:

The Promises/A+ specifiaction which specifies how Q's then works dictates that whenever a value is returned from a .then callback it is unwrapped as a promise.

What calling Q(foo) does, which is similar to what Promise.resolve(foo) does is wrap things as a promise. So Q(100) is a promise over the value 100. Whenver a value is returned from a then callback, it is "wrapped".

Q(100); 
Q().then(function(){ return 100; }); // the same as the line above
Q.try(function(){ return 100; }); // same as line above
// or in ES6 native promises or bluebird promises
Promise.resolve(100);
Promise.resolve().then(function(){ return 100; }); // the same as the line above

To be perfectly clear, the spec says about the .then callback arguments:

If either onFulfilled or onRejected returns a value x, run the Promise Resolution Procedure [[Resolve]](promise2, x).

The Promise Resolution Procedure states:

If x is a promise, adopt its state [3.4]: (note mine: not our case)

Otherwise, if x is an object or function,

  • Let then be x.then . [3.5]

  • if then is not a function, fulfill promise with x

So, Q is OK in doing this, this makes our life easier and allows us to assimilate values as promises. The reasoning is that we want to keep the appearance of .then chains async, so returning a value is really just fulfilling the the new promise we're wrapping

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM