search

Home  >  Q&A  >  body text

node.js - promise可以中途终止函数链吗?

我使用q.js来处理异步调用的问题情况。可能是我对promise的理解不到位,对于reject()的情况我一直觉得处理起来很别扭。先来看下我的处理方式,有不妥之处,欢迎予以指出。
代码如下:

var Q = require('q');

Q.fcall(function(){
    return 2;
}).then(function(v){//f1
    var deferred = Q.defer();
    if(v == 1)
        deferred.resolve("resolve");
    else
        deferred.reject("reject");
    return deferred.promise;
}).then(function(){//f2
    console.log("f2 resolve");
},function(){
    console.log("f2 reject");
    //如果上一函数是reject走到这里,由于函数已报错,我不希望再执行f3函数,这里改怎么写能不让f3执行呢?
    //正常的话,f3函数是会执行的
}).then(function(){//f3
    console.log('end');
});

f1函数执行结果返回了reject的状态,走到了f2的fail函数里了,在这里能阻止再执行f3函数吗?
如果朋友们有好的方式来处理reject的情况,可以show出代码让我学习学习啊。先表示感谢!

PHPzPHPz2864 days ago560

reply all(2)I'll reply

  • 怪我咯

    怪我咯2017-04-17 13:27:59

    Add throw 0 to the second function of the second then and try it. Of course, you can decide the throw thing yourself.

    function(){
        console.log("f2 reject");
        return Q.reject();    // 加上这句试试
        // throw 0;           // 或者这句
    
        //如果上一函数是reject走到这里,由于函数已报错,我不希望再执行f3函数,这里改怎么写能不让f3执行呢?
        //正常的话,f3函数是会执行的
    }

    Generally, a reject check will be added at the end, such as

    q.then(fSuccess).then(fSuccess2).fail(fFail);

    If the first one fails, the second one will be skipped.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 13:27:59

    Try changing it to the following:

    var Q = require('q');
    
    var deferred = Q.defer(); // 创建一个deferred对象
    Q.fcall(function(){
        return 2;
    }).then(function(v){//f1
        if(v == 1)
            deferred.resolve("resolve");
        else
            deferred.reject("reject");
        return deferred.promise; // 通过deferred控制执行
    }).then(function(){//f2
        console.log("f2 resolve");
    },function(){
        console.log("f2 reject2");
        deferred.reject("reject");
        return deferred.promise; // 通过deferred控制执行
    }).then(function(){//f3
        console.log('end');
    });

    reply
    0
  • Cancelreply