Nodejs / Q : Chaining promises sequentially

后端 未结 1 448
挽巷
挽巷 2020-12-09 14:16

I want to do something really simple, but i don\'t understand a little thing ...

var Q = require(\'q\');

var funcs = [\"first\", \"second\", \"third\", \"fo         


        
相关标签:
1条回答
  • 2020-12-09 14:49

    Judging from your example, I would assume that you already saw Sequences part of Q readme, but failed to understand it.

    Original example used "waterfall" model, when the output of each function passed as an input to the next one:

    var funcs = [foo, bar, baz, qux];
    
    var result = Q(initialVal);
    funcs.forEach(function (f) {
        result = result.then(f);
    });
    return result;
    

    But you just want to execute all our functions in sequence, so you could simply bind each function with its variables:

    var args = ["first", "second", "third", "fourth"];
    
    var result = Q();
    args.forEach(function (t) {
        result = result.then(treat.bind(null, t));
    });
    return result;
    

    In my example treat function will be called 4 times sequentially, and result promise will be resolved with the value of latest treat call (results of all previous calls will be ignored).

    The trick is that .then method accepts a handler which will be called after current promise will be resolved and returns a new promise. So, you should pass to .then a function which should be called on the next step of your execution chain. treat.bind(null, t) binds treat function with attribute t. In other words, it returns a new function, which will invoke treat, passing t as its first argument.

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