Returning a value from a Promise

前端 未结 4 1649
猫巷女王i
猫巷女王i 2020-12-31 16:47

I would like to call the Google Maps Geocoding API using a Promise like this:

function makeGeoCodingRequest(address,bounds)
{
    /*
        Input parameters         


        
4条回答
  •  -上瘾入骨i
    2020-12-31 17:10

    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!

提交回复
热议问题