Vasiliy Ivanov Vasiliy Ivanov - 10 months ago 81
Javascript Question

How can I promisify google api requests?

I have grouped addresses. I take one and create a request to google API but I don't execute this request I push to an array for next Promise.all this requests. I guess "googleMapsClient.directions" don't return promise.
How to collect and execute all requests with Promise.all?

urlsPromises.push(
googleMapsClient.directions({
origin: origin,
destination: destination,
waypoints: waypoints,
optimize: true,
mode: 'driving'
}));
});
console.log(urlsPromises);
// return:
// [ { cancel: [Function], finally: [Function] },
// { cancel: [Function], finally: [Function] } ]

Promise.all(urlsPromises).then(results => {
results.forEach((route, index1) => {
const tripIndex = index1;
console.log('- RESULT');
//result:
// - RESULT
// [ { cancel: [Function], finally: [Function] },
// { cancel: [Function], finally: [Function] } ]

Answer Source

You can directly create a Promise object by doing something like this:

const myPromise = new Promise((resolve, reject) => {
  // do what you need here
  if(something) {
    resolve(someValue)
  } else {
    reject(someError)
  }
});

You could even wrap a request and resolve/reject after its completion handling the results before.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download