[英]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.我目前有一个非常简单的 for 循环运行,但它正在从数据库中获取详细信息,因此涉及一些延迟。 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.
显示无论网络活动是什么,或者可能在 for 循环中放置什么延迟。
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. fetch
是异步的。 Anything after your fetch block is not dependent on what is happening in there to complete.在 fetch 块之后的任何事情都不依赖于那里发生的事情来完成。
You have a couple of options.你有几个选择。
Option 1: Move console.log('loop is finished!');
选项 1:移动
console.log('loop is finished!');
to call back in the second then
method.在第二个
then
方法中回调。
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选项 2:如果您希望它在所有异步工作完成后执行,包括处理任何错误,请使用
finally
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!'));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.