首页 > 解决方案 > 如何直接从异步函数返回对象?

问题描述

  var x =[]
  lookup(
      "GET",
      "api/post/",
      (response, status: number) => {
        Object.assign(x, response);
      }
    );
  console.log(x,'her x stay just ampty array []');
switch (action.type) {
    case "SetData":
      return { ...state, data: x };
    default:
      return state;
  }

const newData = async () => {
    var x: any = [];
    await lookup(
      "GET",
      "api/post/",
      (response: myArrays["posts"], status: number) => {
        Object.assign(x, response);
      }
    );
    return x;
  };
  console.log(newData().then((res) => res));


switch (action.type) {
    
    case "SetData":
      return { ...state, data: newData().then((res) => {return res}) };
    default:
      return state;
  }

标签: javascriptreactjsredux

解决方案


以您尝试执行此操作的方式执行此操作是不可能的。你需要做的是这样的:

const data = await newData();
dispatch({ type: "SetData", data })

推荐阅读