0

I am not a JS/TS dev, however I have to add one thing is some frontend project written in TS.

Let me describe it shortly. I have a list of functions which are executed sequentially. The first defined result found is then returned and the rest of functions are not executed then. So let's say, I have functions: [fun1, fun2, fun3, fun4, fun5] and fun1, fun2 return undefined for given args and fun3 returns some value - fun4, fun5 are not executed then and the result from fun3 is returned from a caller function. All functions are synchronous.

Now, I have to add a new function with GET request. I will add it to the mentioned array, but HTTP call makes it a bit problematic. I would have to work with async/await model or promises and then callback, but as I understand, it does not give me any chance to wait for a result in a synchronous method.

Unfortunately, it is not possible to refactor the existing code to make it async.

Is there any way to integrate blocking IO call into the existing synchronous code?

export function myProblematicFunction(...some args...): SomeReturnVal {
    // I want to make a GET call here, post-process it and return it as SomeReturnVal
}
  • 1
    "*Is there any way to integrate blocking IO call into the existing synchronous code?*" not usefully. The synchronous mode for HTTP calls has been deprecated for a very long time and pretty much unavailable nowadays. With a good reason. Having to wait for it means *the entire UI thread would hang* in the browser. And in Node, the processing thread. Hence they are async. Hence the only way to handle them is asynchronously. If you have some architecture that can only work with sync stuff, then you cannot really do some magic and turn an async value into a sync one. – VLAZ Feb 15 '22 at 16:25
  • Whether you use `const resp=await fetch();` or `fetch().then(...)`, HTTP themselves calls are asynchronous. If your code blocked on such a call, it would freeze the browser tab. – Panagiotis Kanavos Feb 15 '22 at 16:26
  • Does this answer your question? [How to block for a javascript promise and return the resolved result?](https://stackoverflow.com/questions/29440632/how-to-block-for-a-javascript-promise-and-return-the-resolved-result) – Panagiotis Kanavos Feb 15 '22 at 16:27
  • Thank you for your help. Unfortunately, I had to redesign the existing solution a bit. Luckily, I managed to do that. – rabbitvirus Feb 22 '22 at 20:05

0 Answers0