How to make javascript fetch synchronous? [duplicate]

 ̄綄美尐妖づ 提交于 2020-05-26 10:24:07

问题


I'm using fetch to get data json from an api. Works fine but I have to use it repeatedly for various calls, thus it needs to be synchronous or else I need some way to update the interface when the fetch completes for each component.

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 ?

Is there any other way to achieve it other than using fetch? (I don't want to use jquery preferrably).

Thanks

Edit

The question is about fetch-api, not ajax, not jquery, so please stop marking it as duplicate of those questions without reading it properly. And if you still feel compelled to do so, please stop linking it to decade old questions and answers, a lot changes in a decade.


回答1:


You want your fetch function to return sth:

function fetchOHLC(yUrl){
    return 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);
    });    
}

Now fetchData contains a promise, which can be easily used:

var fetchData = fetchOHLC(yUrl);
fetchData.then(alert); //not empty ! its {t,o,h,l,c}

If you want some fancy ES7, you could rewrite the whole thing like this:

async function fetchOHLC(yUrl) {
  try {
    const res = await ( await fetch(yUrl) ).json();
    alert(JSON.stringify(r.query));
    return {t:r.created,o:r.open,h:r.high,l:r.low,c:r.close};
  } catch(e) { console.log(e); }
}

(async function () {
  const fetchData = await fetchOHLC(yUrl);
  alert(fetchData);
})()


来源:https://stackoverflow.com/questions/44735669/how-to-make-javascript-fetch-synchronous

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!