簡體   English   中英

鏈承諾與then()

[英]Chain promises with then()

我正在使用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不是函數

錯誤是指twoFn(callback)callback函數。

將這些功能鏈接在一起並一個接一個執行的正確方法是什么?

問題在於, nodefn.lift不知道該函數有多少個參數(零),因此它只接收出現的參數並將其回調附加到它們。 then鏈中,每個回調都會收到前一個諾言的結果(在您的情況下為undefined ),因此將使用兩個參數來調用您的twofnundefined和nodeback。

因此,如果您修復他們的問題,它應該可以工作:

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

基於@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