How to make javascript fetch synchronous?

fetch is intended to do asynchronous calls only, but there 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

Option 4

If you want to send analysis data or session data when leaving a page (e.g. in onbeforeunload) and want to be sure that the data is sent to the server, which is not guaranteed with a normal asynchronous AJAX call, you can use the Beacon API with Navigator.sendBeacon().

Leave a Comment