Bruno Pontes
Bruno Pontes

Reputation: 21

Javascript promises not working in my case

Its a simple case

var q = new Promise(function(resolve, reject){
        resolve(initRequest('get', 'includes/getRemessaRegistrada.php', null, remessasList));
    }).then(function(){
        console.log('ok');
    });

I'm learning javascript promises concept. Why console.log('ok') is coming before resolve processing?

Upvotes: 1

Views: 1156

Answers (1)

jfriend00
jfriend00

Reputation: 707158

In your code initRequest() does not return anything. For your code to work as you have it, initRequest() must return a promise that is tied to the underlying asynchronous operation. And, if it did return a promise, then you don't need another wrapping promise around that.

Promises by themselves do not have magical powers to somehow know when an underlying asynchronous operation completes. They just don't have such powers. A promise only works when there's an asynchronous operation that calls resolve or reject on the promise at the appropriate time when the asynchronous operation completes with a value or an error. The promise then serves as an easier to use interface for managing and coordinating asynchronous results or errors.

You are running initRequest() which starts your async operation and then immediately returns, then long before it finishes, you are calling resolve(undefined) for your wrapping promise. This promise will resolve long before initRequest() is done and will not know anything about the async return value.

The best solution here would be to get or use a promisified version of XMLHttpRequest so you can make ajax calls with functions that just return promises. jQuery has one built in. The latest browsers have fetch() which does Ajax and returns a promise and there are dozens of small libraries available to do this or you could make your own. If you aren't already using a library that has this built in (like jQuery) and you need to get something specifically for this, I'd probably get a fetch() polyfill since this is clearly the future direction for browsers.

If you wanted just a simple XHR wrapper or a way to make ajax calls using a promise interface, here are some ways to go:

How do I promisify native XHR?

XR

Fetch Polyfill


It also occurs to me that because you have return req.responseText in your initRequest() function, you may think that initRequest() is returning that value. It is not. initRequest() returns nothing. return req.responseText is being returned to an async callback which just goes into the bowels of the XMLHttpRequest implementation. Your initRequest() function has long, long since already returned and returned undefined. For more on why this is the case, see How do I return the response from an asynchronous call?.

Upvotes: 2

Related Questions