【问题标题】:add property to array of obejct with async function使用异步函数将属性添加到对象数组
【发布时间】:2021-06-23 05:49:42
【问题描述】:

我想将tripPrice 添加到我数组的每个对象中,但最后,tripPriceundefined

这是我的代码:

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
}

如何在调用 API 后向我的对象添加新属性?它无需异步等待和 API 调用即可工作

【问题讨论】:

标签: javascript node.js ecmascript-6


【解决方案1】:

使用Async/AwaitPromise.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)
}

}

【讨论】:

  • 如果您使用的是await,则无需使用then。另外,您可以从map 返回promise,将map 返回的数组分配给promises
【解决方案2】:

试试这个

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 函数用于从值列表生成修改版本,它与 for 循环不同。 Map 函数将返回更新后的列表,您可以使用该变量,在https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map 上阅读更多内容

【讨论】:

  • 这只返回一个 Promise 数组 {}
  • 好的,在分配给resultWithTripePrice之前尝试await关键字
猜你喜欢
  • 2021-03-22
  • 2018-03-02
  • 2020-08-09
  • 2021-01-13
  • 1970-01-01
  • 1970-01-01
  • 2011-11-09
  • 1970-01-01
相关资源
最近更新 更多