我正在尝试根据另一个API请求的结果发出一个API请求。我以自己想要的方式运行它,但是我不喜欢在API调用中使用forEach,而且我无法解决如何使用其他方法来解决问题。是否有关于如何以更有效的方式进行操作的建议,例如与promise.all?
这是我的代码:
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
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:{...}
}
]
答案 0 :(得分:0)
我尝试了以下提取
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:... }, ...]
有关如何改进代码的任何建议?