0

I have following function that promises:

function getAdressValidity(inputed_adress){

var isValid = false;

return new Promise(function(resolve, reject) {
    MapApi.geocodeAddress(inputed_adress, function(err, data) {

        if(err){
            isValid = false;
        } else {
            isValid = true;
        }
        resolve(isValid);
    });
  });
}

And i consume the promise here:

async function isAdressValid(inputed_adress){
var isValid = await getAdressValidity(inputed_adress);
return isValid;
}

Then, as soon as my page is loaded i output the result to console:

console.log(Order.isAdressValid("1231231232"));

Which gives this output:

enter image description here

If i place console.log like that, it ouputes awaited result:

async function isAdressValid(inputed_adress){
var isValid = await getAdressValidity(inputed_adress);
console.log(isValid);
// return isValid;
}

Is there a way to wait for the result in other thread, while returning the value in the synchronous matter, like my function is expected to do?

TheSmokingGnu
  • 302
  • 2
  • 6
  • 15

1 Answers1

0

You can't mix async and sync code. Whenever there is something async, you need to wrap it asynchronously:

(async function(){

  console.log(await Order.isAdressValid("1231231232"));

})()

or the ES6 way:

Order.isAdressValid("1231231232").then(console.log);
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • To explain the ES6 way. Async is actually a promise under the hood, so calling an async function directly in sync code results in a promise being returned. – Shammoo Nov 23 '17 at 19:15