Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make fetch call really synchronous

Tags:

javascript

Yes, I want to do it completely synchronous. I know that it will completely stop my one and only thread, but I really need that, because I use some SDK which I don't want to change and in this SDK you need to pass a function that will be called and that will change some value in there like that:

function onNonce(stuff) {
    const url = 'fancy url to change stuff';

    // await also doesn't work

    // const response = await fetch(url);
    // const resp_json = await response.json();
    // return resp_json.token;

    // await also doesn't work

    const req = new XMLHttpRequest();
    req.open("GET", url, false); // <-- completely sync and deprecated
    req.send();

    if(req.readyState === 4 && req.status === 200) {
        return req.response.token;
    }
}

And this is how my func is called:

function SDK(result) {
    //
    // SOME FANCY CODE
    //

    var the_value_to_change;

    the_value_to_change = onNonce('some stuff');
    console.log("async");

    //
    // SOME FANCY CODE that uses this the_value_to_change
    //
}

If I use await then my func returns Promise instead of the token, and if I use open with true (async), then I get undefined. The variant with false (completely sync) is deprecated, so I want to do the same stuff with fetch API.

// EDIT //

So, how can I do the execution of onNonce function (fetch and response.json()) completely synchronous?

like image 728
Ruslan Plastun Avatar asked Mar 18 '26 21:03

Ruslan Plastun


1 Answers

You can't.

fetch does not have an option to run synchronously (for the same reason that the option to run XHR synchronously was deprecated in the first place).

Learn how to use await properly instead.

like image 81
Quentin Avatar answered Mar 20 '26 09:03

Quentin