Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
135 views
in Technique[技术] by (71.8m points)

javascript - How can I turn a regular function into a promise/async await?

I've been reading about promises and async/await and such.

But I am bit confused when I have to combined these in certain points and with Typescript as well.

Look at this for instance, which is a functionality to show/hide a modal:

  // myStore.ts

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

See?

There I would like to give the option to use asyn await when I call this method.

Let's say like this:

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

    someOtherFn();
  };

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

But right now if I call it like above, it says that:

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

Get my point?

question from:https://stackoverflow.com/questions/65908233/how-can-i-turn-a-regular-function-into-a-promise-async-await

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Async/await won't do much (if anything at all) in this kind of situation. To really use async/await effectively, you should use it in situations where delay is involved (such as an HTTP request or a database query)

As for the error you are receiving, your function must have return statement at the bottom and the returned value must be a 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();
        }
      }
    />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...