0

asyncFunc1 is the function I am waiting to complete.

const asyncFunc1 = async (data) => {

  let money = data.money
  let res = {}

  if(data.flag === 1) {
    let calRes = await funcToCalTax(data)
    res.calRes = calRes
  } else {
    let calRes = await funcToCalBonus(data)
    res.calRes = calRes
  }
  return res
}

const mainFunc = (data) => {
  let totAmt = []
  let empList = ['abc', 'def', 'ghi']
  empList.forEach(element => {
    totAmt.push(bonus(element))
  });

  if(data.tempFlag > 0) {
    totAmt.push(asyncFunc1(data))

    if(data.check === true) {
      totAmt.push(func2(data))
    }
  }

  return totAmt
}

Since asyncFunc1 returns a promise mainFunc needs to changed accordingly. I am getting stuck while converting it to accept that promise. This is what I have written for mainFunc:

const mainFunc = (data) => {
  let totAmt = []
  let empList = ['abc', 'def', 'ghi']
  empList.forEach(element => {
    totAmt.push(bonus(element))
  });

  if(data.tempFlag > 0) {

    asyncFunc1(data).then(res => {
      totAmt.push(res)

      if(data.check === true) {
        totAmt.push(func2(data))
      }
    })

    // return totAmt
  }
  return totAmt
}

Where am I going wrong? Return is not waiting for the if part to be completed. How do I change it to return only after the if completes?

Renee
  • 199
  • 12
  • 1
    You can't. Asynchronous operations are non-blocking and thus your function will return BEFORE the asynchronous result is ready. Instead, you must use some notification method to communicate back the final result, either a promise, a callback, an event or some other notification invention. The usual way in this case would be a promise since the asynchronous operation already returns a promise. So, your function should just return that promise and the caller uses that promise to get the final result. – jfriend00 May 28 '23 at 17:57

0 Answers0