我有一个异步功能
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()完成之前被调用,因此我的数组为空。
答案 0 :(得分:1)
您需要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)
}