Search code examples
node.jsgoogle-apiasync-awaites6-promise

How do I export the result of a promise chain to a separate module?


I would like to use the result of googleApi.js inside index.js but am having trouble accessing the data from index.js. The result is either undefined or a promise object depending on the solutions I have tried. Could someone please point me in the right direction?

index.js:

const googleClient = require('./googleApi.js')

let one = '52.4362,4.7291'
let two = '52.2672,5.0813'

const test = async() => {
    const result = await googleClient.getTimeAndDistance(one,two)
    console.log(result)
}

test()

googleApi.js

const googleMapsClient = require('@google/maps').createClient({
    key: 'MY_API_KEY',
    Promise: Promise
})

getTimeAndDistance = (origin, destination) => {
    googleMapsClient.directions({
        origin: origin,
        destination: destination,
        language: 'en',
        units: 'metric',
    })
        .asPromise()
        .then((res) => {
            return res.json.routes[0].legs[0]
        })
        .catch((err) => {
            console.log(err)
        })
}

module.exports.getTimeAndDistance = getTimeAndDistance

The code in googleApi.js works and I am able to log the result to the console, but I am unable to access that data outside of the module even when I export the function.


Solution

  • In index.js return googleMapsClient from inside getTimeAndDistance to make available the res.json.routes[0].legs[0] outside the getTimeAndDistance.

    const googleMapsClient = require('@google/maps').createClient({
        key: 'MY_API_KEY',
        Promise: Promise
    })
    
    getTimeAndDistance = (origin, destination) => {
     return googleMapsClient.directions({
    //^^^^^ 
            origin: origin,
            destination: destination,
            language: 'en',
            units: 'metric',
            })
            .asPromise()
            .then((res) => {
                return res.json.routes[0].legs[0]
            })
            .catch((err) => {
                console.log(err)
            })
    }
    
    module.exports.getTimeAndDistance = getTimeAndDistance