'How to make javascript fetch synchronous?
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.
Solution 1:[1]
Callbacks and webworkers instead of the fetch API. https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
Solution 2:[2]
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 https://stackoverflow.com/a/54950884/2590616
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 https://stackoverflow.com/a/52013616/2590616
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Matthew Robin |
| Solution 2 | RiZKiT |
