There are three ways to perform asynchronous operations with JavaScript:
- Callbacks . The function takes the answer as the last argument. It returns nothing (
undefined ), and when the async operation completes, a callback is called. - Promises : the function returns a promise that resolves the result of the async operation upon completion.
- Async / Await : The function returns a promise and can use the
async keyword to get the values โโof asynchronous operations inside its definition. Anything returned with the return keyword will be completed in promise.
Since getDistanceMatrix accepts the callback, it returns nothing. The await keyword used in the code does not have to wait; it immediately gets the undefined value returned by getDistanceMatrix . When the operation completes and the callback is called, getDistance has a long finished result and returns.
You need to wrap getDistanceMatrix so that it makes a promise, also make getAllDistance() return the promise and expect this promise in the console.log() statement:
const coords = [ ['-36.22967', '-125.80271'], ['54.06395', '54.06395'], ['-5.00263', '-137.92806'] ]; function getDistance (start, end) { const origin = new google.maps.LatLng(start[0], start[1]); const final = new google.maps.LatLng(end[0], end[1]); const service = new google.maps.DistanceMatrixService(); return new Promise((resolve, reject) => { service.getDistanceMatrix( { origins: [origin], destinations: [final], travelMode: 'DRIVING' }, (response, status) => { if(status === 'OK') { resolve({ distance: response.rows[0].elements[0].status }); } else { reject(new Error('Not OK')); } } ); }); } function getAllDistance (starts, end) { const promisedDistances = starts.map((start) => getDistance(start, end));
source share