0

I need to call a common function whether synchronous function is invoked or asynchronous function is invoked.

This is how I first wrote but this is not correct as foo will be called before asynchronous function is completed.

function main(element) {
  if (element.id === 'sync') {
    syncFunction();
  } else {
    asyncFunction();
  }
  foo();
}

So, I came up with this but here I feel like I am repeating the call to foo too many times. Is there a better way?

function main(element) {
  if (element.id === 'sync') {
    syncFunction();
    foo();
  } else {
    asyncFunction().then(() => {
      foo();
    });
  }
}

I could use async/await and refactor this even better but where this code eventually will run doesn't support it. Is there a way to better write this using promises?

javanoob
  • 6,070
  • 16
  • 65
  • 88

1 Answers1

1

If you put the result of the call into a Promise.resolve(), you can chain .then onto it unconditionally.

function main(element) {
    Promise.resolve((element.id === 'sync' ? syncFunction : asyncFunction)())
        .then(foo);
}
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Thank You. Not sure if I am doing something wrong but when I try this `foo` is not executed after async function. Here is the jsfiddle I am using : https://jsfiddle.net/q5ne19rf/49/ – javanoob May 19 '22 at 00:01
  • 1
    You forgot to call `resolve` in `asyncFunction`, so the Promise hangs – CertainPerformance May 19 '22 at 00:01