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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With