我正在使用 when promise 库 lift()
我的节点样式回调并 promise 它们...
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();
但是调用第二个回调函数时报错:
Uncaught TypeError: undefined is not a function
错误是指 twoFn(callback)
中的 callback
函数。
将这些函数链接在一起并一个接一个执行的正确方法是什么?
最佳答案
问题是 nodefn.lift
不知道函数有多少个参数(零),所以它只接受出现的参数并将其回调附加到它们。在 then
链中,每个回调都会收到前一个 promise 的结果(在您的情况下: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);
关于javascript - 用 then() 链式 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28628627/