2

I have an Array of elements and I need to loop over them getting a value from a server at each pass. With the following code I am getting all the results mixed, due to the asynchronous call in the forEach loop. I need the results to be shown in the same order as in the Array.

var en_devices= [
  ["72", "Device 1"],
  ["73", "Device 2"],
  ["74", "Device 3"],
  ["75", "Device 4"],
  ["76", "Device 5"],
  ["5158", "Device 6"]
];

en_devices.forEach(element => {
    $.get('/check-energy/'+element[0], function(data){
      content = "<div class='service'>"+element[1]+"</div> <div class='watt'>"+data+"</div><br/>";
      $('#description-en').append(content);
  });
 });

1 Answer 1

1

You should try for loop with await

var en_devices= [
  ["72", "Device 1"],
  ["73", "Device 2"],
  ["74", "Device 3"],
  ["75", "Device 4"],
  ["76", "Device 5"],
  ["5158", "Device 6"]
];

Create a function that returns a promise so that you can await it

function getData(element) {
    return new Promise((resolve, reject) => {
      $.get('/check-energy/'+element[0], function(data) {
        resolve(data)
    })
})
}

Now run a for loop

let content="";
for(let i=0;i<en_devices.length;i++)
{
let data=await getData(en_devices[i])
content += "<div class='service'>"+element[1]+"</div> <div class='watt'>"+data+"</div><br/>";
     
}


$('#description-en').append(content);

async wait doesn't works in forEach loop ,you can either use for of or for loop

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.