Best way to handle case where same code must run either immediately or after a promise resolved

Viewed 53

Depending on a certain condition x, I need to perform a redirect either right now or after a promise asyncFunction resolved:

if (x) {
  await asyncFunction();
  redirectToA();
}
redirectToA();

That's quite ugly though. Is there a way to simplify this code so that redirectToA(); appears only once?

2 Answers

I think you could simply do this:

if (x) {
  await asyncFunction();
}
redirectToA();

This is an example showing you that the redirectToA() will wait:

async function asyncFunction() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve()
    }, 3000)
  })
}

function redirectToA() {
  document.getElementById('status').innerText = "Redirected"
}


(async function() {
  // your code is here
  if (true) {
    await asyncFunction()
  }
  redirectToA()
})()
<p id="status">
  Running
</p>

It may not be an issue but I would be inclined to call redirectToA() at nextTick+ under both conditions.

await (x ? asyncFunction() : Promise.resolve());
redirectToA();

Thus, you are better guaranteed consistent redirect behaviour and may possibly benefit from less testing.

Related