簡體   English   中英

如何在javascript中修復無序的“fetch”

[英]how to fix unordered “fetch” in javascript

我使用for循環獲取多個路由並保存其結果這是我的代碼

 for (let i = 0; i < datesToFetch.length; i++) {


fetch("http://localhost:3000/areaChart/"+datesToFetch[i]+"/"+datesToFetch[i+1])
.then(response => response.json())
.then(response => console.log(response))

}

我真的很奇怪,我得到的數據順序是隨機順序它不是按照循環升序來的,這在這種情況下非常重要

我應該怎么做才能獲得正確的數據?

歡迎使用異步代碼!

您可以做的一件事是創建一個datesToFetch.length long的空數組,並將response.json()的值賦給適當的索引。

const responses = [...Array(datesToFetch.length)]

for (let i = 0; i < datesToFetch.length; i++) {
  fetch("http://localhost:3000/areaChart/"+datesToFetch[i]+"/"+datesToFetch[i])
    .then(response => response.json())
    .then(response => responses[i] = response)
}

你的情況:

您正在調用具有不同解決時間的多個函數。 就像麥當勞在不同的隊列中驚恐一樣,有些gyus同時到達,因為你可以在自己之前或之后吃飯。

 function getRandomInt(max) { return Math.floor(Math.random() * Math.floor(max)); } function display(i) { return new Promise((resolve) => { setTimeout(() => { resolve(i); }, getRandomInt(1500)); }); } for (let i = 0; i < 5; i += 1) { display(i) .then(x => console.log('->', x)); } 


一個解決方案:

我們正在使用一個名為Promise.all的功能來等待所有人吃飯,然后走出商店。

 function getRandomInt(max) { return Math.floor(Math.random() * Math.floor(max)); } function display(i) { return new Promise((resolve) => { setTimeout(() => { resolve(i); }, getRandomInt(1500)); }); } const promises = []; for (let i = 0; i < 5; i += 1) { promises.push(display(i)); } // We use Promise.all to wait for all responses // The responses are in the call order Promise.all(promises) .then((rets) => { rets.forEach(x => console.log('->', x)); }); 

發生了什么,以及如何解決它:

你的代碼正在排隊一堆fetch ,但是在繼續循環的下一次迭代之前不等待它們完成。 他們可以按任何順序完成。

如果您希望循環停止並等待每次,請將其包裝在async函數中,並await獲取。

async function test() {

    for (let i = 0; i < datesToFetch.length; i++) {
        var response = await fetch("http://localhost:3000/areaChart/"+datesToFetch[i]+"/"+datesToFetch[i+1]);
        var responseJson = await response.json();
        console.log(responseJson);
    }

}

模擬您的代碼:

 const delay = t => new Promise(resolve => setTimeout(resolve, t)); async function test() { for (let i = 1; i <= 5; i++) { console.log(`Starting call #${i}`); delay(5000 - (i * 1000)) .then(() => console.log(`Call #${i} has completed.`)); } } test(); 

上面提供的解決方案的模擬:

 const delay = t => new Promise(resolve => setTimeout(resolve, t)); async function test() { for (let i = 1; i <= 5; i++) { console.log(`Starting call #${i}`); await delay(5000 - (i * 1000)); console.log(`Call #${i} has completed.`); } } test(); 

那是因為這個fetch調用將被添加到JavaScript事件循環中。 將顯示返回結果的第一個,因此順序可以與它們被調用的順序不同。

要解決此問題,您應該查看await運算符。 更多信息可以在這里找到: https//dev.to/johnpaulada/synchronous-fetch-with-asyncawait

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM