Is there a way to return early in deferred promise?

你说的曾经没有我的故事 提交于 2019-11-27 02:13:00

Try not to create a single deferred, that could be rejected from multiple parts of your function, and which you would need to return at every exit point.
Instead, code with separate promises, one for each branch of control flow you have. You can use Q.reject and the Q.Promise constructor - avoid the deprecated deferred pattern. Your function would then look like this:

function test() {
    var deferred = q.defer()
    var passed = false
    if (!passed)
        return Q.reject("Don't proceed");
    if (!passed)
        return Q.reject("Don't proceed");
    if (!passed)
        return Q.reject("Don't proceed");
    // else
    return new Promise(function(resolve) {
        setTimeout(function(){
            console.log("Hello");
            resolve();
        }, 100);
    });
}

Alternatively, you can wrap your test function in Q.fbind, so that instead of writing return Q.reject(…); you could just do throw …;.

function test(){
    var deferred = q.defer()
    var passed = false
    if(true){
        deferred.reject(new Error("Don't proceed1"))
        return deferred.promise
    }
    if(!passed){
        deferred.reject(new Error("Don't proceed2"))
        return deferred.promise
    }
    if(!passed){
        deferred.reject(new Error("Don't proceed3"))
        return deferred.promise
    } 
    setTimeout(function(){
        console.log("Hello");
        deferred.resolve()
    });
    return deferred.promise
}

I think this is the best way, thank to Bergi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!