简体   繁体   English

链承诺与then()

[英]Chain promises with then()

I'm using the when promise library to lift() my node style callbacks and promisify them... 我正在使用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);
}

I want to call the functions in a chain, like this: 我想像这样调用链中的函数:

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

But it gives me an error when calling the second callback function: 但这在调用第二个回调函数时给我一个错误:

Uncaught TypeError: undefined is not a function 未捕获的TypeError:undefined不是函数

The error refers to the callback function within twoFn(callback) . 错误是指twoFn(callback)callback函数。

What is the correct way to chain these functions together and execute one after the other? 将这些功能链接在一起并一个接一个执行的正确方法是什么?

The problem is that nodefn.lift doesn't know how many parameters the function has (zero), so it just takes the appearing arguments and appends its callback to them. 问题在于, nodefn.lift不知道该函数有多少个参数(零),因此它只接收出现的参数并将其回调附加到它们。 In a then chain every callback receives the result of the previous promise (in your case: undefined ), so your twofn will be called with two arguments: undefined and the nodeback. then链中,每个回调都会收到前一个诺言的结果(在您的情况下为undefined ),因此将使用两个参数来调用您的twofnundefined和nodeback。

So if you fix their arities, it should work: 因此,如果您修复他们的问题,它应该可以工作:

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

Based on @Bergi's answer, I wrote this function: 基于@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);
    };
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM