0

I want to add tripPrice to every object of my array but in the end, tripPrice is undefined

here is my code:

async getTest(req, res) {

       let result = await this.model.Pricing.getTest(req.params);  
       result.map(async item => {
            let params = {
                originStation: item.fromStation,
                destStation: item.toStation,
                cityCode: 1,
                carClass: item.carType,
              }
            let tripPrice = await axios.post(`${appConfig.gpsServer.host}/api/trip/price`, params);
            item.price = tripPrice
            return item
        })
   return result
}

how can I add new property to my object after calling an API? it works without async await and API calling

John
  • 93
  • 6
  • Is it `tripPrice` which is `undefined` or are you checking `item.price` before the async call succeeds? [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/q/23667086) See also [Use async await with Array.map](https://stackoverflow.com/q/40140149) – VLAZ Jun 23 '21 at 05:54
  • 1
    [Using async/await with a forEach loop](https://stackoverflow.com/questions/37576685) – adiga Jun 23 '21 at 05:57
  • You need to await all the promises `await Promise.all(result.map(async item => {...` – Vivek Bani Jun 23 '21 at 05:59

2 Answers2

1

Try this

async getTest(req, res) {

       let result = await this.model.Pricing.getTest(req.params);  
       resultWithTripePrice = result.map(async item => {
            let params = {
                originStation: item.fromStation,
                destStation: item.toStation,
                cityCode: 1,
                carClass: item.carType,
              }
            let tripPrice = await axios.post(`${appConfig.gpsServer.host}/api/trip/price`, params);
            item.price = tripPrice
            return item
        })
        return resultWithTripePrice
}

Map function is used to make a modified version from a list of values, its not same something like for loop. Map function will return the updated list and you can use that variable, readmore on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Abhin Krishna KA
  • 745
  • 8
  • 13
1

Using Async/Await and Promise.all

const getTest = async (req, res) => {

try {
    let result = await this.model.Pricing.getTest(req.params);
    const promises = [];

    result.map(item => {
        const params = {
            originStation: item.fromStation,
            destStation: item.toStation,
            cityCode: 1,
            carClass: item.carType,
        }
        const promise = new Promise((resolve, reject) => {
            axios.post(`${appConfig.gpsServer.host}/api/trip/price`, params).then(tripPrice => {
                item.price = tripPrice || null;
                resolve(item)
            }).catch(e => {
                reject(e)
            })
        })
        promises.push(promise);
    })


    const result = await Promise.all(promises).then(r => r).catch(error => { throw error })
    console.log(result)
    return result;
} catch (error) {
    console.log(error)
}

}
Ashok Kumar
  • 326
  • 2
  • 8
  • 1
    No need to use `then` if you are using `await`. Also, you can return the promise from the `map` assign the array returned by `map` to `promises`. – adiga Jun 23 '21 at 13:42