简体   繁体   中英

Using a fetch promise synchronously

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.

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM