Home > front end >  Using a fetch promise synchronously
Using a fetch promise synchronously

Time:05-31

I need a synchronous function (it can be blocking).

I need to use Fetch, and when the promise is ready, I want to return it on the synchronous function.

Everywhere I look I can't find the answer.

CodePudding user response:

I need a synchronous function

Unlikely.

(it can be blocking).

That is what synchronous means.

Long running blocking functions (including network operations) cause serious usability problems and should be avoided.

I need to use Fetch, and when the promise is ready, I want to return it on the synchronous function.

That is not possible.

XMLHttpRequest has a synchronous mode, although it is deprecated and should not be used.

You can activate it by passing false as the third parameter to open.

xhr.open("METHOD as string", "URL as strong", false);

fetch learned lessons from XMLHttpRequest and did not implement anything similar.


Learn how to deal with asynchronous code instead. The async and await keywords will let you write in in a synchronous style.

CodePudding user response:

You can't block the main thread like this, the browser won't allow you(or nodejs, since I don't know which). There's no synchronous way to fetch like that. You can instead use async/await to have your code avoid callbacks. It's probably highly unadvised to do what you want to and there's a better solution, but I can't tell you much more because of lacking context.

  • Related