3
The following is example taken from the Google Maps node module

function doSomeGeoCode() {

  const googleMapsClient = require('@google/maps').createClient({
    key: 'your API key here',
    Promise: Promise
  });

  googleMapsClient.geocode({address: '1600 Amphitheatre Parkway, Mountain 
   View, CA'})
  .asPromise()
  .then((response) => {
    console.log(response.json.results);
  })
  .catch((err) => {
    console.log(err);
  });
}

如何使用 async 和 await 调用 doSomeGeoCode。我还需要在收到响应后调用另一个函数。请建议

4

1 回答 1

9

你只需要返回 promisifiedgoogleMapsClient并创建另一个方法来等待响应,例如:

function doSomeGeoCode() {
  const googleMapsClient = require('@google/maps').createClient({
    key: 'your API key here',
    Promise: Promise,
  });

  // Return the promise
  return googleMapsClient.geocode({
      address: '1600 Amphitheater Parkway, Mountain View,CA ',
    })
    .asPromise();
}

async function myTest() {
  try {
    // Called the method which returns promise.
    // `await` will wait to get promise resolved.
    const result = await doSomeGeoCode();
    console.log(result);
  } catch (error) {
    // If promise got rejected.
    console.log(error);
  }
}

myTest();
于 2018-11-19T21:37:03.347 回答