[英]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.