Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
284 views
in Technique[技术] by (71.8m points)

javascript - Is there a way to return early in deferred promise?

So I have a promise which contains multiple checks like this

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

This looks bad because there is a pyramid at the bottom. I'm wondering is there something like return in 'q' which can make the code look better? For example like this:

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

This definitely doesn't work because it returned before promise is returned, but I'm wondering is there something like a return?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 …;.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...