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?
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);
}