Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
248 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...