我正在尝试根据另一个API请求的结果发出API请求。我让它以我想要的方式工作,但我不喜欢将 forEach 用于我的 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());
};
应用.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 }));
}, []);
存档输出:
orders:[
0: {
order:{...},
worker:{...}
},
...
...
...
20: {
order:{...},
worker:{...}
}
]
我尝试了以下获取
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));
它重新调整了我想要得到的东西。 一个数组,每个对象的值为 Order 和 worker
[20]
[ { order:...., worker:... }, ...]
关于如何改进代码的任何建议?