PrestonDocks
PrestonDocks

Reputation: 5428

Call async function from within bluebird Promise.each()

I have an async function

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)
  }

and I need to call that function multiple times from with in a bluebird.each() loop

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)
}

The result is

[]
188
99

So as you can see the last console.log statement is called before before Proimise.each() has completed and so my array is empty.

Upvotes: 0

Views: 345

Answers (1)

Lux
Lux

Reputation: 18240

You need to 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)
}

Upvotes: 1

Related Questions