This question already has an answer here:
- How to “await” for a callback to return? 4 answers
I've got the following code block:
new Promise((res, rej) => {
if (checkCondition()) {
res(getValue())
} else {
getValueAsync((result) => {
res(result)
})
}
}).then((value) => {
doStuff(value)
})
I'd like to convert this to use async
/await
, but I can't figure out how to do it. I know when you're working exclusively with promises, you replace the calls to then()
with value = await ...
, but How do I make this work with callbacks? Is it possible?
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:This, however, assumes that you can modify
getValueAsync
as well, to make it anasync
function or to make it return aPromise
. AssuminggetValueAsync
has to take a callback, there is not that much we can do:You still gain the benefit of not having to create the full
Promise
chain yourself. But,getValueAsync
needs to be wrapped in aPromise
in order to be usable withawait
. 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 alreadyasync
/ returnPromise
s.