3

In my Javascript app I sometimes find I need to modify a section of code that is initially run synchronously and add some code that runs asynchronously.

Before:

function doSomething() {
   var x = 0;

   ...

   return true;
}

After:

async function doSomething() {
   var x = 0;
   await doSomethingElse();

   ...

   return true;
}

Many times this is fine. Problems occur however if the function doSomething is being called by another function that expects doSomething to complete and return a result. Originally the code was running synchronously, so this is not an issue. But now that I have added async to doSomething, it will return immediately even before the doSomethingElse call has completed. Yet I don't want doSomething to return until doSomethingElse has completed and any code following it. The only solution I can think of is to modify the calling code to handle doSomething as a Promise. The problem with this is that I end up having to do the same thing for the function that calls that function and so on up the hierarchy.

Is there a way to add the doSomethingElse in such a way that the doSomething will still execute synchronously?

A similar post seems to suggest that this is not possible (But that was 3 years ago. Maybe something has evolved since then to make it possible):

How to block for a javascript promise and return the resolved result?

Johann
  • 27,536
  • 39
  • 165
  • 279

2 Answers2

0

The only option you got is to "fire and forget" somewhen:

 function doSomething() {
   var x = 0;
   doSomethingElse();
    // ...
   return true;
}
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
0

your doSomething method also return a promise.
So use it as normal promise

doSomething().then(boolean=>{

}).catch(e=>{

})

or

async function other(){
    try{
        let boolean = await doSomething();
        // your other code
    }catch(e){
        // your error handler
    }
}
ashe
  • 108
  • 5