节点8:将promise/callback结构转换为async/await [英] node 8: converting a promise/callback structure to async/await

查看:80
本文介绍了节点8:将promise/callback结构转换为async/await的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码块:

new Promise((res, rej) => {
  if (checkCondition()) {
    res(getValue())
  } else {
    getValueAsync((result) => {
      res(result)
    })
  }
}).then((value) => {
  doStuff(value)
})

我想将其转换为使用 async / await ,但是我不知道该怎么做.我知道当您仅使用诺言时,您将对 then()的调用替换为 value = await ... ,但是如何使用回调来实现此目的?有可能吗?

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?

推荐答案

首先,必须确保开始使用 async 函数.然后可能是这样的:

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();

但是,这假设您还可以修改 getValueAsync ,使其成为 async 函数或使其返回 Promise .假设 getValueAsync 必须进行回调,那么我们无能为力:

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();

您仍将获得不必自己创建完整的 Promise 链的好处.但是,为了与 await 一起使用, getValueAsync 需要包装在 Promise 中.您应该仔细考虑这种更改对您是否值得.例如.如果您可以控制大多数代码库和/或要调用的大多数功能已经 async /返回了 Promise s.

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.

这篇关于节点8:将promise/callback结构转换为async/await的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆