-1

I know that the solution to my problem is the promises but I can't understand at all how to apply it to what I want to do ... Can you help me without referring me to the courses on promises in javascript?

thx you

function getPosition (workers) {
    let counter = 0
    let allResult = []
    _.forEach(workers, (n) => {
        let firstname = n.firstname
        let lastname = n.lastname
        let streetname = n.address.streetname
        let city = n.address.city
        let country = n.address.country
        axios.get('https://api-adresse.data.gouv.fr/search/?q=' + streetname + ' ' + city)
            .then(response => {
                let lon = response.data.features[0].geometry.coordinates[0]
                let lat = response.data.features[0].geometry.coordinates[1]
                let finalResult = {
                    firstname: firstname,
                    lastname: lastname,
                    address: {streetname: streetname, country: country, city: city, lon: lon, lat: lat}
                }
                logger.info('Longitude and latitude was found for ' + firstname + ' ' + lastname)
                counter++
                allResult.push(finalResult)
                if (counter === workers.length) {
                    return(allResult)
                }
            })
            .catch(error => {
                logger.error(error)
            })
    })
}

I just want to return 'allresult' ... thanks for your help

MikeK
  • 3
  • 1
  • 1
    promises are resolved not returned. Alternatively you can use async/await – shrekDeep Feb 20 '20 at 15:24
  • Does this answer your question? [Node.js - Wait for multiple async calls to finish before continuing in code](https://stackoverflow.com/questions/50924814/node-js-wait-for-multiple-async-calls-to-finish-before-continuing-in-code) – zero298 Feb 20 '20 at 15:25

1 Answers1

2

You can't really return a promise, you can resolve it instead like so:

function getPosition(workers) {
    return Promise.all(workers.map(worker => {
        const {firstname, lastname, address: {streetname, city, country}} = worker;
        return axios.get(`https://api-adresse.data.gouv.fr/search/?q=${streetname} ${city}`)
            .then(response => {
                const [lon, lat] = response.data.features[0].geometry.coordinates;
                return {
                    firstname: firstname,
                    lastname: lastname,
                    address: {streetname, country, city, lon, lat}
                };
            })
            .catch(logger.error)
    })).then(results => results.filter(Boolean));
}

And access the results in a form of

getPosition(workers)
    .then(allResults => {
        // do what you need with the results
    })

Or alternatively with async/await syntax

(async ()=>{
    const allResults = await getPosition(workers)
    // do what you need with the results
})()
Krzysztof Krzeszewski
  • 5,912
  • 2
  • 17
  • 30