node 8: converting a promise/callback structure to

2019-08-29 05:05发布

This question already has an answer here:

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?

1条回答
戒情不戒烟
2楼-- · 2019-08-29 05:21

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.

查看更多
登录 后发表回答