连锁承诺与当时()

时间:2015-02-20 12:08:19

标签: javascript promise browserify when-js

我使用when promise库来lift()我的节点样式回调并宣传它们......

var nodefn = require('when/node');

var one = nodefn.lift(oneFn),
    two = nodefn.lift(twoFn),
    three = nodefn.lift(threeFn);


function oneFn(callback){
    console.log('one');
    callback(null);
}

function twoFn(callback){
    console.log('two');
    callback(null);
}

function threeFn(callback){
    console.log('three');
    callback(null);
}

我想调用链​​中的函数,如下所示:

one().then(two).then(three).done();

但是在调用第二个回调函数时它给了我一个错误:

  

未捕获的TypeError:undefined不是函数

错误是指callback中的twoFn(callback)函数。

将这些功能链接在一起并逐个执行的正确方法是什么?

2 个答案:

答案 0 :(得分:2)

问题是nodefn.lift不知道函数有多少参数(零),所以它只需要出现的参数并将其回调附加到它们。在then链中,每个回调都会收到先前承诺的结果(在您的情况下为undefined),因此您的twofn将使用两个参数调用:undefined和nodeback。

所以,如果你修复他们的arities,它应该工作:

Function.prototype.ofArity = function(n) {
    var fn = this, slice = Array.prototype.slice;
    return function() {
        return fn.apply(null, slice.call(arguments, 0, n));
    };
};
var one = nodefn.lift(oneFn).ofArity(0),
    two = nodefn.lift(twoFn).ofArity(0),
    three = nodefn.lift(threeFn).ofArity(0);

答案 1 :(得分:0)

根据@ Bergi的回答,我写了这个函数:

function nodeLift(fn){
    return function(){
        var args = Array.prototype.slice.call(arguments, 0, fn.length - 1),
            lifted = nodefn.lift(fn);

        return lifted.apply(null, args);
    };
}
相关问题