Javascript Q then()总是调用失败

Javascript Q then()总是调用失败,javascript,node.js,promise,q,Javascript,Node.js,Promise,Q,在下面的示例中,为什么“good”和“Error”被称为“编写控制台” 我的理解是,你给了then()一些成功的东西和失败的东西 var deferred = Q.defer(); function two() { deferred.resolve(); return deferred.promise; } two().then(console.log('good'),console.log('Error is called')); 您必须将函数传递给。然后。您所做的是调用

在下面的示例中,为什么“good”和“Error”被称为“编写控制台”

我的理解是,你给了then()一些成功的东西和失败的东西

var deferred = Q.defer();

function two() {
    deferred.resolve();
    return deferred.promise;
}

two().then(console.log('good'),console.log('Error is called'));

您必须将函数传递给
。然后
。您所做的是调用
console.log('good')
,并将调用它的结果(未定义)传递给
。然后
。这样使用:

two().then(
    function() { console.log('good'); },
    function() { console.log('Error is called'); }
);
所有这些都应该是函数

  • 成功处理者

  • 故障处理程序

  • 进度处理程序

  • 当你这样做的时候

    two().then(console.log('good'), console.log('Error is called'));
    
    实际上,您正在将执行
    console.log
    s的结果传递给
    then
    函数。
    console.log
    函数返回
    undefined
    。所以,实际上,你正在这样做

    var first  = console.log('good');              // good
    var second = console.log('Error is called');   // Error is called
    console.log(first, second);                    // undefined, undefined
    two().then(first, second);                     // Passing undefineds
    
    因此,您必须将两个函数传递给
    然后
    函数。像这样

    two().then(function() {
        // Success handler
        console.log('good');
    }, function() {
        // Failure handler
        console.log('Error is called')
    });
    
    但是,
    Q
    实际上提供了一种方便的方法,可以在一个点上处理承诺中出现的所有错误。这使开发人员不用太担心业务逻辑部分的错误处理。这可以通过函数来实现,就像这样

    two()
        .then(function() {
            // Success handler
            console.log('good');
        })
        .fail(function() {
            // Failure handler
            console.log('Error is called')
        });