[英]Wait for for loop to complete before continuing
我目前有一個非常簡單的 for 循環運行,但它正在從數據庫中獲取詳細信息,因此涉及一些延遲。 這是一個非常基本的腳本,因此不涉及其他問題中顯示的大量額外代碼。
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!');
當然,如果你通常運行它,你會得到預期的日志,
"Animal 1 is a dog"
"Animal 2 is a cat"
"Animal 3 is a fish"
"Animal 4 is a squirrel"
"loop is finished!"
但是,由於從服務器訪問陣列的一些延遲,我得到:
"loop is finished!"
"Animal 1 is a dog"
"Animal 2 is a cat"
"Animal 3 is a fish"
"Animal 4 is a squirrel"
在轉到代碼中的下一個任務之前,如何確保整個循環完成?
我要“循環完成!” 顯示無論網絡活動是什么,或者可能在 for 循環中放置什么延遲。
這是“原始代碼”:
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
是異步的。 在 fetch 塊之后的任何事情都不依賴於那里發生的事情來完成。
你有幾個選擇。
選項 1:移動console.log('loop is finished!');
在第二個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)
});
選項 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.