首页 > 解决方案 > 如何在异步函数中从此返回的对象中提取数据?

问题描述

我正在尝试在 JavaScript 中做一些工作 - 我从异步函数调用异步函数,如下所示。

  useEffect(() => {
    (async () => {
      await asyncFunction();
      // do stuff
    })();
  }, []);

asyncFunction 看起来像这样

const asyncFunction = (dispatch) => {
  return async (data) => {
    try {
      const response = await APICall();

      dispatch({ type: "search", payload: response.data });
    }
    // error handling
}

asyncFunction 分派给reducer,reducer返回return { errorMessage: "", data: action.payload };

通过我自己的测试,我看到它console.log(asyncFunction())返回了一个承诺,并且console.log(await asyncFunction())什么也没有返回。

我注意到的一件奇怪的事情是,在程序的每个部分中放置 console.log 语句时,首先打印出来自函数调用(在 useEffect 块中)的承诺,然后是来自 console.log 语句的 reducer 中的数据补充一下return { errorMessage: "", data: action.payload };

所以我的问题是,我如何访问这些数据?我在这里查看了一些其他推荐使用的线程.then,但没有成功。有没有办法在不传入回调函数的情况下做到这一点(这样做意味着我需要重组整个程序)。

这篇文章有点长,所以如果您有任何问题,或者需要我的程序的其他部分,请告诉我。

标签: javascriptreactjsreact-native

解决方案


您可以在不返回函数并直接完成其中的过程的情况下执行相同的过程。

修改使用效果代码如下:

useEffect(() => {
    (async () => {
      await asyncFunction(dispatch);
      // do stuff
    })();
  }, []);
const asyncFunction = async (dispatch, data) => {
    try {
      const response = await APICall();
      dispatch({ type: "search", payload: response.data });
    }
    // error handling
}

因为在您提到的函数中,您将数据分派给reducer,而不是返回数据。因此,您可以在那里进行处理工作。

如果你想返回一些数据,你可以参考下面的代码:

以前的代码:

const asyncFunction = (dispatch, data) => {
  return new Promise((resolve, reject) => {
    APICall()
      .then((reponse)=>{
        dispatch({ type: "search", payload: response.data });
        //This will return value to the calling function. This will act as a return statement
        resolve(response);
      })
      .catch((err)=>{
        //This will be executed if there is any error.
        reject(err)
      })
  })

更改代码(正如@Bergi 所说,以避免 Promise 构造函数反模式):

useEffect(() => {
    let mounted = true;
    APICall()
        .then((response) => {
            if (mounted) {
                dispatch({ type: "search", payload: response.data });
                //do some stuff here
            }
        })
        .catch((err) => {
            //handle error here
        })
    return () => mounted = false;
}, []);

Promise将是从异步函数返回数据的最佳方式。


推荐阅读