简体   繁体   English

如何在异步 function 中从返回的 object 中提取数据?

[英]How can I extract data from this returned object in an async function?

I'm trying to do some work in JavaScript - I call an async function from an async function, as shown below.我正在尝试在 JavaScript 中做一些工作 - 我从异步 function 调用异步 function,如下所示。

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

asyncFunction looks like this asyncFunction 看起来像这样

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

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

asyncFunction dispatches to a reducer, which returns return { errorMessage: "", data: action.payload }; asyncFunction 分派给reducer,reducer 返回return { errorMessage: "", data: action.payload };

With my own testing, I've seen that console.log(asyncFunction()) returns a promise, and console.log(await asyncFunction()) returns nothing.通过我自己的测试,我看到console.log(asyncFunction())返回了 promise,而console.log(await asyncFunction())什么也没返回。

One weird thing I have noticed is when placing console.log statements in each part of the program, the promise from the function call (in the useEffect block) is printed out first, then the data in the reducer from the console.log statement I added right about return { errorMessage: "", data: action.payload };我注意到的一件奇怪的事情是,在程序的每个部分中放置 console.log 语句时,首先打印出来自 function 调用(在 useEffect 块中)的 promise,然后打印出来自 console.log 语句的减速器中的数据 I增加了关于return { errorMessage: "", data: action.payload }; . .

So my question is, how do I access this data?所以我的问题是,我如何访问这些数据? I've looked at some other threads on here which recommend using .then , but that was unsuccessful.我在这里查看了其他一些建议使用.then的线程,但没有成功。 Is there a way to do it without passing in a callback function (doing so would mean I need to restructure the whole program).有没有办法在不传递回调 function 的情况下做到这一点(这样做意味着我需要重组整个程序)。

This post is a bit long, so if you have any questions, or need additional parts of my program, please let me know.这篇文章有点长,所以如果您有任何问题,或者需要我的程序的其他部分,请告诉我。

You can do the same process without returning the function and directly completing the process in it.您可以执行相同的过程,而无需返回 function 并直接在其中完成该过程。

Change the use effect code as follows:修改使用效果代码如下:

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
}

Because in the function you mentioned you are dispatching data to reducer and not returning the data.因为在 function 中,您提到您正在将数据分派给减速器而不是返回数据。 So instead you can just do the processing work there.因此,您可以在那里进行处理工作。

In case you want to return some data, you can refer the code below:如果你想返回一些数据,你可以参考下面的代码:

Previous Code:以前的代码:

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)
      })
  })

Changed Code (as @Bergi said to avoid Promise constructor anti-pattern):更改代码(正如@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;
}, []);

Promises would be the best way to return data from async function. Promise 是从异步function返回数据的最佳方式。

I could be totally wrong, but I think that you might be running into issues returning the async function, explained here in docs .我可能完全错了,但我认为您可能会遇到返回异步 function 的问题, 在 docs 中进行了解释

Also, it looks like you might be calling asyncFunction (inside your useEffect hook) without a value for dispatch?此外,看起来您可能正在调用 asyncFunction (在您的 useEffect 挂钩内)而没有调度值? Here:这里:

  (async () => {
      await asyncFunction();
      // do stuff

I regurgitated a custom hook for API calls following your plan: link to sandbox .我按照您的计划为 API 调用反刍了一个自定义钩子: link to sandbox Hopefully it can be helpful!希望它会有所帮助!

AsyncFunction is returning a function, not the data that comes from the API call. AsyncFunction 返回 function,而不是来自 API 调用的数据。 What you can do, if I understand your problem correctly, is return the response from the call and remove the initial return statement.如果我正确理解您的问题,您可以做的是从调用中返回响应并删除初始返回语句。

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

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