简体   繁体   中英

Wait for for loop to complete before continuing

I currently have a very simple for loop running, but it is getting details from a database so involves some delay. It's a very basic script so doesn't involve a lot of extra code shown in other questions.

 var animals = ['dog', 'cat', 'fish', 'squirrel']; for (var x in animals) { console.log('Animal ' + (Number(x) + 1) + ' is a ' + animals[x]); } console.log('loop is finished!');

Of course, if you run this usually, you get the expected log, of

"Animal 1 is a dog"
"Animal 2 is a cat"
"Animal 3 is a fish"
"Animal 4 is a squirrel"
"loop is finished!"

However, with some delays on accessing the array from the server, I am getting:

"loop is finished!"
"Animal 1 is a dog"
"Animal 2 is a cat"
"Animal 3 is a fish"
"Animal 4 is a squirrel"

How do I ensure the whole loop is complete before moving onto the next tasks in the code?

I want "loop is finished!" to show no matter what the network activity is, or what delays may be put within the for loop.

Here's the 'original code':

 fetch('http://localhost:3000/pet/'+pet) .then(res => res.json()) .then(data => { const newData = (data); for (var x in newData) { finalpetName.push(newData[x].petName); console.log('pet' + x + 'is retrieved'); }; }) .catch(err => { console.error(err) }); console.log('loop is finished!');

fetch is asynchronous. Anything after your fetch block is not dependent on what is happening in there to complete.

You have a couple of options.

Option 1: Move console.log('loop is finished!'); to call back in the second then method.

fetch('http://localhost:3000/pet/'+pet)
  .then(res => res.json())
  .then(data => {
    const newData = (data);
    for (var x in newData) {
      finalpetName.push(newData[x].petName);
      console.log('pet' + x + 'is retrieved');
    };
    console.log('loop is finished!');
  })
  .catch(err => {
    console.error(err)
  });

Option 2: Use finally if you want it to execute after all the asynchronous work is done, including handling any errors

fetch('http://localhost:3000/pet/'+pet)
  .then(res => res.json())
  .then(data => {
    const newData = (data);
    for (var x in newData) {
      finalpetName.push(newData[x].petName);
      console.log('pet' + x + 'is retrieved');
    };
  })
  .catch(err => {
    console.error(err)
  })
  .finally(() => console.log('loop is finished!'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM