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
262 views
in Technique[技术] by (71.8m points)

javascript - Resolve promise based on another promise

I've a function, which returns a promise, inside that I call another function, and the status of this promise is based on the status of the inner promise.

Is there a way to shorthand this process. Look at the example below.

    function foo(bar) {
        var deferred = Q.defer();

        switch (bar) {
            case 'baz1':
                deferred.resolve();
                break;
            case 'baz2':
                deferred.reject();
                break;
            case 'this_is_how_i_do_it':
                funReturningPromise().then(function (value) {
                    deferred.resolve(value);
                }, function (err) {
                    deferred.reject(err);
                });
                break;
            case 'can_we_do_it_like_this':
                // can we do something like this, which will resolve or reject the deferred, 
                // based on the status promise returned by funReturningPromise().
                // 'chain' is just a name
                funReturningPromise().chain(deferred);
                break;
        }

        return deferred;
    }

Thanks,

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

It doesn't work as well for more complex functions, but in your example you could do something like:

        case 'can_we_do_it_like_this':
            return funReturningPromise();

You can also try adding your own promise.prototype.chain method if you're using only q promises.


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

...