0

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?

ewok
  • 20,148
  • 51
  • 149
  • 254
  • [async/await is not magic](https://stackoverflow.com/a/37104225/542251) seems to be the important thing to note here – Liam Feb 09 '18 at 16:58
  • @Liam so it sounds like the answer is what I want is impossible, and I'm stuck with promises for now? – ewok Feb 09 '18 at 16:59

1 Answers1

1

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 Promises.

Aurel Bílý
  • 7,068
  • 1
  • 21
  • 34