javascript - 用 then() 链式 promise

标签 javascript promise browserify when-js

我正在使用 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/

相关文章:

javascript - 谷歌浏览器包应用程序 : How to make transparent rounded background like google hangout app?

javascript - 找不到模块 : Error: Cannot resolve module 'routes'

javascript - 检查用户名中包含的特定密码文本模式以进行 javascript 表单验证

JavaScript 多级 Promise 跳过了 .then()

javascript - 不使用 Javascript 填充 HTML 中的列表

javascript - Gulp + babelify + browserify 问题

javascript - 正则表达式删除字母,数字以外的符号

javascript - 如何调用 rest api 并将结果提供给后续的 promise 调用

javascript - 如何在编译时动态导入js文件作为browserify的输入?

javascript - JS promise 返回