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!');