Returning a value from a Promise Returning a value from a Promise ajax ajax

Returning a value from a Promise


If you depend on a promise in order to return your data, you must return a promise from your function.

Once 1 function in your callstack is async, all functions that want to call it have to be async as well if you want to continue linear execution. ( async = return a promise )

Notice that your if statement does not have braces and thus only the first statement after it will not be executed if the condition fails.

I fixed it in this example. Notice the remarks I added.

if(address){    promise=Q($.ajax({        type: "GET",        url: "https://maps.googleapis.com/maps/api/geocode/json?address=" + address + "&key=API_KEY"    }));    return promise.then(function(data) {        // whatever you return here will also become the resolve value of the promise returned by makeGeoCodingRequest        // If you don't want to validate the data, you can in fact just return the promise variable directly        // you probably want to return a rejected promise here if status is not what you expected        if (data.status === "OK") return data;            else console.error(messages[data.status]);        return null;        });}

You must call makeGeoCodingRequest in the following fashion.

makeGeoCodingRequest(address,bounds).then(function(data){    // this will contain whatever     console.log(data);});


I find that I obtain a promise instead of a value

Yes, because the operation is asynchronous and returns a promise which represents the future value.

Why isnt promise.then executed before the value was returned?

Because it's asynchronous. .then will (must) never execute its callback before it returns another promise.

How can I obtain a value from this promise instead of another promise?

You are getting the value in the callback:

makeGeoCodingRequest(address).then(function(geo) {    console.log(geo)    console.log(Q.isPromise(geo)); // false    // do anything with the value here})// if you need to do anything with the result of the callback computation:// you're getting back another promise for that!

It's impossible to obtain it synchronously from the promise (many have tried). That would mean blocking execution, which we don't want - let's stay async and non-blocking!


You are returning a promise from the function makeGeoCodingRequest. That is a good thing according to me, this helps you chain any more async calls if required in future. What I would suggest is to use a .then() on the returned promise and check if the promise has any returned value or error in the following manner.

var geoPromise = makeGeoCodingRequest(address); geoPromise.then(   onSuccess(result){       // You can use the result that was passed from the function here..    },    onFailure(response){      // Handle the error returned by the function.   });