Nodejs/Q:链式顺序承诺 [英] Nodejs / Q : Chaining promises sequentially

查看:127
本文介绍了Nodejs/Q:链式顺序承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做一些非常简单的事情,但是我一点都不懂...

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();

我希望funcs数组中的每个元素都被顺序处理",然后输出将类似于:

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 :(

推荐答案

从您的示例来看,我认为您已经看到

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;

在我的示例中,treat函数将被顺序调用4次,并且result promise将使用最新的treat调用的值进行解析(所有先前调用的结果都将被忽略).

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).

诀窍在于,.then方法接受一个处理程序,该处理程序将在当前的Promise解析后返回并返回一个新的Promise.因此,您应该将一个函数传递给.then,该函数应在执行链的下一步中调用. treat.bind(null, t)treat函数与属性t绑定.换句话说,它将返回一个新函数,该函数将调用treat,并将t作为其第一个参数.

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.

这篇关于Nodejs/Q:链式顺序承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆