[英]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
),因此將使用兩個參數來調用您的twofn
: undefined
和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.