【问题标题】:Q then() always calls failQ then() 总是调用失败
【发布时间】:2023-03-30 20:54:02
【问题描述】:

为什么在下面的例子中,'good' 和 'Error is called' 写控制台?

我的理解是你给 then() 一些东西在成功时运行和在失败时运行?

var deferred = Q.defer();

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

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

【问题讨论】:

    标签: javascript node.js promise q


    【解决方案1】:

    Q.then function can actually accept three parameters都应该是函数

    1. 成功处理程序

    2. 故障处理程序

    3. 进度处理程序

    当你这样做时,

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

    您实际上是将执行console.logs 的结果传递给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
    

    因此,您必须将两个函数传递给then 函数。像这样

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

    但是,Q 实际上提供了一种方便的方法来处理在单点发生的所有错误。这让开发人员不必担心业务逻辑部分中的错误处理。这可以通过Q.fail 函数来完成,就像这样

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

    【讨论】:

      【解决方案2】:

      您必须将函数传递给.then。您所做的是您调用了console.log('good') 并将调用它的结果(即undefined) 传递给.then。这样使用它:

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

      【讨论】:

        猜你喜欢
        • 2023-03-31
        • 1970-01-01
        • 1970-01-01
        • 2019-12-02
        • 1970-01-01
        • 2013-07-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多