gpt4 book ai didi

javascript - 从 bluebird Promise.each() 中调用异步函数

转载 作者:行者123 更新时间:2023-12-02 23:40:26 26 4
gpt4 key购买 nike

我有一个异步函数

async hoursTillNextService(aircraft_id, serviceType) {
var service = await AircraftService.query().where('service_type', serviceType).where('aircraft_id', aircraft_id).orderBy('service_date', 'desc').first()
if (!service) {
return null
}
var lastDate = service.service_date
var logs = await Flyinghour.query().where('aircraft_id', aircraft_id).where('flight_start', '>', moment(lastDate).format("YYYY-MM-DD HH:mm:ss")).sum('engine_minutes as totalMinutes')
return parseInt(((serviceType * 60) - logs[0].totalMinutes) / 60)
}

我需要在 bluebird.each() 循环中多次调用该函数

async serviceFlyingHoursProfile({ params, view }) {
var aircraft = await Aircraft.query().where('id', params.id).with('serviceIntervals').first()
// console.log(aircraft.serviceIntervals())
var intervals = await aircraft.serviceIntervals().fetch()

var serviceHourProfile = []
await Promise.each(intervals.rows, async (interval) => {

this.hoursTillNextService(aircraft.id, interval.hours).then((hours) => {
console.log(hours)
serviceHourProfile.push(hours)
return
})
})
console.log(serviceHourProfile)
}

结果是

[]
188
99

正如您所看到的,最后一个 console.log 语句是在 Proimise.each() 完成之前调用的,因此我的数组是空的。

最佳答案

您需要await this.hoursTillNextService:

async serviceFlyingHoursProfile({ params, view }) {
var aircraft = await Aircraft.query().where('id', params.id).with('serviceIntervals').first()
// console.log(aircraft.serviceIntervals())
var intervals = await aircraft.serviceIntervals().fetch()

var serviceHourProfile = []
await Promise.each(intervals.rows, async (interval) => {

await this.hoursTillNextService(aircraft.id, interval.hours).then((hours) => {
console.log(hours)
serviceHourProfile.push(hours)
return
})
})
console.log(serviceHourProfile)
}

关于javascript - 从 bluebird Promise.each() 中调用异步函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56103791/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com