Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the promise still pending?

Tags:

javascript

q

The following code returns:

output.isPending?: true
output.isRejected?: false
output.isFulfilled?: false 

Why? I was expecting output.isRejected to be true.

<html>

<head>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/q.js/0.9.7/q.js"></script>
    <script src="http://jasmine.github.io/2.3/lib/jasmine.js"></script>
</head>

<body>
</body>
<script>
var output, bar;

bar = {
    doSomethingAsync: function() {
        var d = Q.defer();
        d.resolve('result');
        return d.promise;
    }
};

function Foo(bar) {
    this._bar = bar;

    this.go = function() {
        var deferred = Q.defer();
        this._bar.doSomethingAsync()
            .then(onSuccess.bind(this, deferred));

        return deferred.promise;
    }
};

function onSuccess(deferred, result) {
    deferred.reject();
}

output = new Foo(bar).go()
    .finally(function() {
        console.log('output.isPending?:', output.isPending());
        console.log('output.isRejected?:', output.isRejected());
        console.log('output.isFulfilled?:', output.isFulfilled());
    });
</script>

</html>
like image 996
Ben Aston Avatar asked May 19 '15 15:05

Ben Aston


People also ask

What does it mean promise pending?

The promise will always log pending as long as its results are not resolved yet. You must call .then on the promise to capture the results regardless of the promise state (resolved or still pending): let AuthUser = function(data) { return google. login(data. username, data.

How do you resolve a promise?

Promise resolve() method: Any of the three things can happened: If the value is a promise then promise is returned. If the value has a “then” attached to the promise, then the returned promise will follow that “then” to till the final state. The promise fulfilled with its value will be returned.

How do I access my promise results?

Define an async function. Use the await operator to await the promise. Assign the result of using the await operator to a variable.

Does promise all keep order?

Consequently, it will always return the final result of every promise and function from the input iterable. Note: The order of the promise array is preserved upon completion of this method.


1 Answers

Because output is not new Foo(bar).go(). It is assigned the result of the .finally() call, and will not be resolved untill the finally callback is done.

This will work as expected:

var output = new Foo(bar).go();
output.finally(function() {
    console.log('output.isPending?:', output.isPending());
    console.log('output.isRejected?:', output.isRejected());
    console.log('output.isFulfilled?:', output.isFulfilled());
});
like image 155
Bergi Avatar answered Sep 20 '22 09:09

Bergi