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

查看:26
本文介绍了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 :(

推荐答案

从你的例子来看,我假设你已经看到了 Q readme 的序列部分,但未能理解.

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 承诺将使用最新的 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 方法接受一个处理程序,该处理程序将在当前承诺被解析并返回一个新承诺后被调用.因此,您应该向 .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天全站免登陆