How to make javascript fetch synchronous?

I use fetch to get json data from api. It works great, but I have to use it several times for various calls, so it needs to be synchronous, or I need to somehow update the interface when the selection is complete 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 this than using sampling? (I do not want to use jquery preferred).

thank

Edit

The question is about fetch-api, not ajax, not jquery, so please stop marking it as a duplicate of these questions without reading it correctly. And if you still feel compelled to do this, please stop associating it with ten-year old questions and answers, much will change in a decade.

+4
1

, fetch 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);
    });    
}

fetchData , :

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

- ES7, :

async function fetchOHLC(yUrl){
  try{
    var r=JSON.parse(await fetch(yUrl))
    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(){
  var fetchData = await fetchOHLC(yUrl);
  alert(fetchData);
})()
+6

Source: https://habr.com/ru/post/1680019/


All Articles