skip to Main Content

I know it is a repeated question but still i am writing my query

Issue as Unexpected await inside a loop

const createChartPanel = async (data) => { 

   for (let a = 0.0; a < totalMacroFactorCount;) {
      let panel=[]

      //some bunch code here

       await addCharts(scenarioNameLoop, tableBody[0],
            barColor, orangeBar, maroonBar, darkBlueBar, chartBodyAndHeight.calculateChartHeight, a === 0);
       panel.push(chartPanel);
    }
return panel;
}   

Before addChart is done panel.push(chartPanel) is called, how should I called panel.push(chartPanel) once addChart process is completed

4

Answers


  1. Add async to your parent function

    const yourFunc = async () => {
     for (let a = 0.0; a < totalMacroFactorCount; a++) {
      let panel=[]
    
      //some bunch code here
      await // yourcode
    
      await addCharts(scenarioNameLoop, tableBody[0],
            barColor, orangeBar, maroonBar, darkBlueBar, 
      chartBodyAndHeight.calculateChartHeight, a === 0);
      panel.push(chartPanel);
     }
    }
    

    also disable eslint error by adding

    /* eslint-disable no-await-in-loop */
    
    Login or Signup to reply.
  2. How do you mean "Can not write await in for loop"?

    You are getting an error?

    If so, the parent function is probably not declared as async or you are trying to execute code in the global context.

    Login or Signup to reply.
  3. First of all, you need to add an increment into your for loop.

    for (let a = 0.0; a < totalMacroFactorCount; a++) {//Code}
    

    Provide some more information pls to help you more properly you maybe can code a workaround but i need more information on what is going on to help you

    Login or Signup to reply.
  4. If you want multiple promises, created by loop (or other means) to be awaited, then you need to capture those promises into Array and then use Promise.all function.

    For some action to take place after the promise has been resolved, you need to use .then method on said promise (or you can move it to separate async function where you await those two actions accordingly).

    const createChartPanel = async (data) => { 
       let panel = []
       let promises = []
       for (let a = 0.0; a < totalMacroFactorCount; a += /* increment */) {
           //some bunch code here
    
           let promise = addCharts(/* your arguments */).then(() => {
               panel.push(chartPanel)
           });
           promises.push(promise)
        }
        await Promise.all(promises)   // await for all promises to finish
        return panel;
    }  
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search