簡體   English   中英

從bluebird Promise.each()中調用異步函數

[英]Call async function from within bluebird Promise.each()

我有一個異步功能

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

因此,您可以看到在Proimise.each()完成之前,調用了最后一個console.log語句,因此我的數組為空。

您需要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)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM