首页 > 解决方案 > 基于 GET 请求数组的 POST 请求

问题描述

我有一系列客户和地址端点 URL,如下所示

  customerArray = [
  {name:customer1, id: 1, address: {streetName: '123 lane'}}, 
  {name:customer2, id: 2, address: {streetName: 'xyz lane'}}, 
  {name:customer3, id: 3, address: {streetName: 'abc lane'}}
]
URL = 'id/addresses'

如果我们得到空数组作为响应,则对 URL 的 GET 请求将返回基于客户 ID 的地址数组,然后我们需要为该 ID 添加来自“customerArray”的地址

 // This is what I am doing to meet the requirement - seems this is not the right approach. Please help me to fix this
customerArray.forEach((customer) => {
  const getObj = {
    url: `${customer.id}/addresses`,
    method: GET
  };

  axios(getObj)
    .then((getResult) => {
      if (getResult.length === 0) {
        const postObj = {
          url: `${customer.id}/addresses`,
          method: POST,
          data: customer.address
        };
        axios(postObj)
          .then((postResult) => {

            // I am not sure what to do here - I leaving blank so iteration will continue
          })
          .catch((err) => {
            res.status(400).json(err);
          });
      }
    })
    .catch((err) => {
      res.status(400).json(err);
    });

});

请帮我修复它

标签: javascriptnode.jsreactjsaxios

解决方案


我想你不知道如何获得最终数据。基本上,您应该将您的承诺放入一个数组中,然后Promise.all等待所有承诺完成。

如果有问题请评论。希望这可以帮助

const promises = customerArray.map((customer) => {
  const getObj = {
    url: `${customer.id}/addresses`,
    method: GET
  };

  return axios(getObj)
    .then((getResult) => {
      if (getResult.length === 0) {
        return {
          url: `${customer.id}/addresses`,
          method: POST,
          data: customer.address
        };
      }
      return null;
    })
    .then((postObj) => {
      if (postObj) {
        return axios(postObj)
      }
      return null
    })
});

Promise.all(promises)
  .then(result => {
    // the result is a list of data from axios(postObj)
    console.log(result);
    res.json(result);
  })
  .catch((err) => {
    res.status(400).json(err);
  });

推荐阅读