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.

1

3 Answers

If you don't want to use the fetch api you will have to use callbacks, event listeners, XMLHttpRequest, and some event like mutations to change the page when content is changed on the page.

1

fetch is intended to do asynchronous calls only, but the are some options:

Option 1

If XMLHttpRequest is also fine, then you can use async: false, which will do a synchronous call.

Option 2

Use async/await which is asynchronous under the hood, but feels like it is synchronous, see

Option 3

or else I need some way to update the interface when the fetch completes for each component

This sound like fetch + Promise.all() would be a good fit, see

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.

15

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy