Why is the promise not yet made?

The following code is returned:

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

Why? I expected output.isRejected be true .

 <html> <head> <script src="http://cdnjs.cloudflare.com/ajax/libs/q.js/0.9.7/q.js"></script> <script src="http://jasmine.imtqy.com/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> 
+5
source share
2 answers

Because output not new Foo(bar).go() . It is assigned the result of a call to .finally() and will not be resolved until the finally callback completes.

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()); }); 
+5
source

I believe that the trivial delay function is not needed even for APIs that do not pay attention to promises. I can make sure that resolve or reject always called, but after the promise itself is returned without delay. Here is an example:

 var somePromise = function(path) { var deferred = q.defer(); asyncFunction.request(path, function(result) { if (result.error === 0 && result.json !== null) { deferred.resolve(result); } else { deferred.reject(result || {error: -1, message: "bad things happened"}); } }); return deferred.promise; }; exports.someCall = function(req,res) { somePromise('path') .then(function (result) { ... do action ... }).catch(function (error) { ... handle error ... }); }; 
0
source

All Articles