Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

221
Views
How to call a common function effectively whether synchronous or asynchronous function is executed using Promises?

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!