chaining promises with q.js

后端 未结 2 1586
一整个雨季
一整个雨季 2021-02-19 23:32

I\'m trying to understand how promise chaining works. I\'m using q.js. Here\'s what I\'m playing with.

var Q = require(\"q\"); // npm install q

// the functio         


        
相关标签:
2条回答
  • 2021-02-20 00:10

    It's because then doesn't expect another promise as an argument. Rather it expects handler functions, an callback and/or an errback, the former you are passing in your 2nd example. Indeed any argument that is not a function is simply ignored.

    From the docs:

    If you return a value in a handler, outputPromise will get fulfilled.

    If you throw an exception in a handler, outputPromise will get rejected.

    If you return a promise in a handler, outputPromise will “become” that promise. Being able to become a new promise is useful for managing delays, combining results, or recovering from errors.

    So yes, chaining promises can be done. You're doing it right in your 2nd example.

    It's possible that the contrived example here of passing fulfilled promises makes the way chaining promises works seem overly verbose, but in real world usage, you typically chain promises because you're interested in their return values, e.g.:

    somethingAsync().then(function (n) {
      return somethingElseAsync(n);
    })
    .then(function (n) {
      return somethingElseAsync(n);
    })
    .then(function (result) {
      // ...
    })
    

    (Actually this mirrors async.waterfall. If you just wanted to call a series of async functions in order with no regards to their results you could use async.series)

    0 讨论(0)
  • 2021-02-20 00:29

    I know javascript doesn't have static types, but you need to think about types here.

    Q(1);                             // has type Promise[Int]
    function (n) { return Q(2); }     // has type Int => Promise[Int]
    

    Q.then needs the second.

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