Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
436 views
in Technique[技术] by (71.8m points)

javascript - 我正在尝试基于另一个使用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.

(我以自己想要的方式运行它,但是我不喜欢在API调用中使用forEach,而且我无法解决如何使用其他方法来解决问题。)

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

(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 }));
  }, []);

archived output:

(存档的输出:)

orders:[
 0: {
  order:{...},
  worker:{...}
},
 ...
 ...
 ...
 20: {
  order:{...},
  worker:{...}
}
]
  ask by Maurice Oppenberger translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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?

(关于如何改进代码的任何建议?)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...