简体   繁体   English

我可以将异步函数作为回调传递给异步函数吗?

[英]Can I pass an async function as a callback to an async function?

I couldn't find an answer to this anywhere...我在任何地方都找不到答案...

I'm trying to use setState to update the state of my app but, I need to call an async function after setState is finished.我正在尝试使用 setState 来更新我的应用程序的状态,但是在setState完成后我需要调用一个async函数。
Can I await an async function inside the callback for setState ?我可以在setState的回调中await async函数吗?

 setState({foo: bar}, async () => {await doStuff()});

Also assuming that this works, can I rely on setState finishing before doStuff is called, and can I rely on doStuff being await ed?还假设这有效,我可以在调用doStuff之前依靠setState完成吗,我可以依靠正在await doStuff吗?

Yes, indeed you can.是的,确实可以。 The special thing about async functions is that they always return Promises, so especially for functions whose return value is not important (callbacks, for example), you can safely put in an async function, and it would work as expected.异步函数的特殊之处在于它们总是返回 Promise,所以特别是对于返回值不重要的函数(例如回调),您可以安全地放入异步函数,它会按预期工作。

Taking this one step further, you can even have an async function as your componentDidMount or componentWillReceiveProps for example (but still not render , which expects a JSX element to be returned, not a Promise).更进一步,你甚至可以有一个异步函数作为你的componentDidMountcomponentWillReceiveProps (但仍然不是render ,它期望返回一个 JSX 元素,而不是一个 Promise)。

The callback of the setState only fires when the state is updated so doStaff will not execute until state is updated. setState 的回调仅在状态更新时触发,因此 doStaff 在状态更新之前不会执行。 You can define the callback as async function and await inside it as any other function.您可以将回调定义为 async 函数,并在其内部像任何其他函数一样等待。

const setStateAsync = (newState) => {
   return new Promise((resolve) => {
       setState(newState, resolve);
   });

you can use it like this Ex:你可以像这样使用它例如:

 async componentDidMount() {
    await setStateAsync(newState);
    await doStuff()
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM