How to make javascript fetch synchronous?

JavascriptJsonAsynchronousFetch Api

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

If you came here because you dropped "how to make javascript fetch synchronous" into a search engine:

That doesn't make much sense. Performing network operations is not something which requires CPU work, thus blocking it during a fetch(...) makes little sense. Instead, properly work with asynchrony as shown in the duplicate linked above.


In case you really need a synchronous request (you don't), use the deprecated XMLHttpRequest synchronous variant, to quote MDN:

> Note: Starting with Gecko 30.0 (Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27), Blink 39.0, and Edge 13, synchronous requests on the main thread have been deprecated due to their negative impact on the user experience.

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

You can find more information on MDN.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNabeel KhanView Question on Stackoverflow
Solution 1 - JavascriptJonas WilmsView Answer on Stackoverflow