First of all, you have to make sure you are in an async
function to begin with. Then it could be something along the lines of:
async function example() {
let value = (checkCondition() ? getValue() : await getValueAsync());
doStuff(value);
}
await example();
This, however, assumes that you can modify getValueAsync
as well, to make it an async
function or to make it return a Promise
. Assuming getValueAsync
has to take a callback, there is not that much we can do:
async function example() {
let value = (checkCondition()
? getValue()
: await new Promise(res => getValueAsync(res))
);
doStuff(value);
}
await example();
You still gain the benefit of not having to create the full Promise
chain yourself. But, getValueAsync
needs to be wrapped in a Promise
in order to be usable with await
. You should carefully consider whether this kind of a change is worth it for you. E.g. if you are in control of most of the codebase and / or most of the functions you are calling are already async
/ return Promise
s.