简体   繁体   English

我正在尝试根据使用 forEach 的另一个 API 请求的结果发出 API 请求。 我如何在不使用 forEach 的情况下存档相同的结果

[英]I am trying to make an API request based on the result of another API request using forEach. How I could archive the same result without using forEach

I am trying to make an API request based on the result of another API request.我正在尝试根据另一个 API 请求的结果发出 API 请求。 I got it working the way I want it but I don't like to use forEach for my API call and I can't wrap my head around how to get in done with a different method.我让它按照我想要的方式工作,但我不喜欢将 forEach 用于我的 API 调用,而且我无法全神贯注于如何使用不同的方法完成工作。 Are there any suggestions on how I could do it in a more efficient way, eg.有没有关于我如何以更有效的方式做到这一点的建议,例如。 with promise.all?与 promise.all?

here is my code:这是我的代码:

api.js api.js

export const fetchOrders = () => {
  return fetch(`${url}/work_orders`).then(res => res.json());
};

export const fetchWorker = id => {
  return fetch(`${url}/workers/${id}`).then(res => res.json());
};

app.js应用程序.js

function OrderReducer(state, action) {
  if (action.type === "fetch") {
    return {
      orders: [],
      error: null,
      loading: true
    };
  } else if (action.type === "success") {
    return {
      ...state,
      orders: [
        ...state.orders,
        {
          order: action.order,
          worker: action.worker
        }
      ],
      loading: false
    };
  } else if (action.type === "error") {
    return {
      ...state,
      error: action.message,
      loading: false
    };
  } else {
    throw new Error("no action type initialized");
  }
}

const Orders = () => {
  const [state, dispatch] = React.useReducer(OrderReducer, {
    orders: [],
    error: null,
    loading: true
  });

  React.useEffect(() => {
    dispatch({ type: "fetch" });

    fetchOrders()
      .then(({ orders }) => {
        return orders;
      })
      .then(orders =>
        orders.forEach(order => {
          fetchWorker(order.workerId).then(({ worker }) =>
            dispatch({ type: "success", order, worker })
          );
        })
      )
      .catch(({ message }) => dispatch({ type: "error", message }));
  }, []);

archived output:归档输出:

orders:[
 0: {
  order:{...},
  worker:{...}
},
 ...
 ...
 ...
 20: {
  order:{...},
  worker:{...}
}
]

I tried the following fetch我尝试了以下获取

const fetchWorker = async order => {
  const res = await fetch(`${url}/workers/${order.workerId}`);
  const { worker } = await res.json();
  return { order, worker };
};

const fetchOrders = async () => {
  const res = await fetch(`${url}/work_orders`);
  const { orders } = await res.json();
  return Promise.all(orders.map(order => fetchWorker(order)));
};

fetchOrders()
  .then(data => console.log(data))
  .catch(({ message }) => console.log(message));

and it retuned what I was trying to get.它重新调整了我想要得到的东西。 an array, each object with a value of order and worker一个数组,每个对象都有一个值 order 和 worker

[20]
[ { order:...., worker:... }, ...]

any suggestions on how to improve the code?关于如何改进代码的任何建议?

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

相关问题 api中的foreach obj如何发出另一个请求 - how foreach obj from api make another request 在 foreach 循环中进行 api 调用并将结果推送到另一个数组中 - make an api call in foreach loop and push the result in another array 使用API​​结果创建另一个请求并一起显示 - Using API result to create another request and display them together 在foreach中请求api - request api in foreach 在API中提出请求并计算结果 - Make request in the API and calculate on the result 如何从这个特定的 API 请求中获得结果? - How do I get a result from this specific API request? 如何在 Visual Studio 中编码此 api 请求的结果 - How can I code the result of this api request in visual studio 如何使用Request-Promise将一个API的响应作为另一个API中的请求参数传递 - How do I pass the response of one API as a request param in another API using Request-Promise node / express.js-带有API请求的forEach循环将结果推送到数组,但数组保持为空 - node/express.js - forEach loop with request to API pushes result to array, but array remains empty 如何根据另一个请求的响应向 API 发出请求? 不能在回调中调用 React Hook “useSwr” - How can I make a request to an API based on the response from another request? React Hook “useSwr” cannot be called inside a callback
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM