Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
490 views
in Technique[技术] by (71.8m points)

node.js - Nodejs / Q : Chaining promises sequentially

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

var Q = require('q');

var funcs = ["first", "second", "third", "fourth"];

function main(){

// really don't know how to chain sequentially here ...
    var result = Q();

    funcs.forEach(function (f) {
        result = treat(f).then(f);
    });

}

function treat(t){

    var deferred = Q.defer();

    setTimeout(function(){
        deferred.resolve("treated "+ t); 
    },2000);

    return deferred.promise;
}

main();

I would like each element of my funcs array to be "treated" sequentially, the output would then be something like :

treated first
//2 seconds later
treated second
//2 seconds later
treated third
//2 seconds later
treated fourth

I cannot achieve that :( it should be simple , i don't catch something :(

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...