簡體   English   中英

如何使 javascript 獲取同步?

[英]How to make javascript fetch synchronous?

我正在使用 fetch 從 api 獲取數據 json。工作正常,但我必須重復使用它進行各種調用,因此它需要同步,否則我需要一些方法來在每個組件的 fetch 完成時更新接口。

function fetchOHLC(yUrl){
    fetch(yUrl)
    .then(response => response.json())
    .then(function(response) {
                alert(JSON.stringify(response.query));

            var t = response.created;
            var o = response.open;
            var h = response.high;
            var l = response.low;
            var c = response.close;
        
        return {t,o,h,l,c};
    
    })
    .catch(function(error) {
        console.log(error);
    });    
}

var fetchData = fetchOHLC(yUrl);
alert(fetchData); // empty ?

除了使用 fetch 之外,還有其他方法可以實現嗎? (我不想最好使用 jquery)。

謝謝

編輯

問題是關於 fetch-api 的,不是 ajax,不是 jquery,所以請不要在沒有正確閱讀的情況下將其標記為這些問題的重復項。

如果您不想使用 fetch api,您將不得不使用回調、事件偵聽器、XMLHttpRequest。

fetch僅用於執行異步調用,但有一些選項:

選項1

如果XMLHttpRequest也可以,那么您可以使用async: false ,它將執行同步調用。

選項 2

使用async/await ,它在后台是異步的,但感覺它是同步的,請參閱https://stackoverflow.com/a/54950884/2590616

選項 3

否則我需要一些方法在每個組件的獲取完成時更新界面

這聽起來像fetch + Promise.all()會很合適,請參閱https://stackoverflow.com/a/52013616/2590616

您始終可以使用 xhr 的舊時尚方式。 這是一個請求的例子。

   var xhttp = new XMLHttpRequest();
   xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        document.getElementById("demo").innerHTML = this.responseText;
       }
     };

   xhttp.open("POST", "cookies.php", true);
   xhttp.send();

您只需添加回調 function 作為參數。

function fetchOHLC(yUrl, callback){
    fetch(yUrl)
    .then(response => response.json())
    .then(function(response) {
            alert(JSON.stringify(response.query));

            var t = response.created;
            var o = response.open;
            var h = response.high;
            var l = response.low;
            var c = response.close;
        
            callback({t,o,h,l,c});
    
    })
    .catch(function(error) {
        console.log(error);
        callback(null, error);
    });    
}

fetchOHLC(yUrl, function(response, error){
    if (response == null) {
        console.log(error);
    } else {
        var fetchData = response;
        alert(fetchData);
    }
});

如果您來到這里是因為您將“如何使 javascript fetch 同步”放到搜索引擎中:

這沒有多大意義。 執行網絡操作不需要 CPU 工作,因此在fetch(...)期間阻止它幾乎沒有意義。 相反,請正確使用異步,如上面鏈接的副本所示。


如果您確實需要同步請求(您不需要),請使用已棄用的XMLHttpRequest同步變體來引用 MDN:

注意:從 Gecko 30.0 (Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27)、Blink 39.0 和 Edge 13 開始,由於對用戶體驗的負面影響,主線程上的同步請求已被棄用。

const request = new XMLHttpRequest();
request.open('GET', '/bar/foo.txt', false);  // `false` makes the request synchronous
request.send(null);

您可以在MDN上找到更多信息。

暫無
暫無

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

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