【问题标题】:How can I turn a regular function into a promise/async await?如何将常规功能变成承诺/异步等待?
【发布时间】:2021-01-27 04:05:03
【问题描述】:

我一直在阅读有关 Promise 和 async/await 等的内容。

但是当我必须将这些在某些方面与 Typescript 结合起来时,我有点困惑。

例如看这个,这是一个显示/隐藏模式的功能:

  // myStore.ts

  @action
  openDialog (body?: React.ReactElement): void {
    this.modalConfig.open = true;
    this.modalConfig.body = body;
  }

看到了吗?

我想在调用此方法时提供使用 asyn await 的选项。

让我们这样说:

  const fn = async (): Promise<void> => {
    await myStore.openDialog(
      <SomeComp onFinish={() => myStore.closeDialog()} />
    );

    someOtherFn();
  };

...
      <OtherComp
        someProp={
          async () => {
            await fn();
            someOtherFunction();
          }
        }
      />

但是现在如果我像上面这样称呼它,它会说:

'await' has no effect on the type of this expression

明白我的意思吗?

【问题讨论】:

  • 看起来您的代码中没有任何异步执行任何操作。 await openDialog 没有任何异步调用,它只是设置了两个属性。如果您删除所有的 await/async 关键字,它是否按预期工作?
  • 你很可能会得到这个,因为在 fn 上等待返回未定义 - myStore.openDialog 是否返回代码状态的承诺?
  • 您可能正在openDialog 中寻找await new Promise(resolve =&gt; this.closeDialog = resolve); this.modalDialog.open = false; this.modalDialog.body = null;。但这不是在 react(?) 中处理商店的一种非常惯用的方式。

标签: javascript asynchronous ecmascript-6 async-await es6-promise


【解决方案1】:

在这种情况下,Async/await 不会做太多(如果有的话)。要真正有效地使用 async/await,您应该在涉及延迟的情况下使用它(例如 HTTP 请求或数据库查询)

至于你收到的错误,你的函数必须在底部有return语句,返回值必须是一个promise

const fn = async (): Promise<void> => {
  await myStore.openDialog(
    <SomeComp onFinish={() => myStore.closeDialog()} />
  );

  someOtherFn();
  
  return new Promise((resolve, reject) => {
    // Handle promise here
  })
};

...
    <OtherComp
      someProp={
        async () => {
          await fn();
          someOtherFunction();
        }
      }
    />

【讨论】:

    猜你喜欢
    • 2018-03-05
    • 2017-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-17
    • 2019-03-20
    • 1970-01-01
    • 2018-02-03
    相关资源
    最近更新 更多