基于GET请求数组的POST请求

时间:2018-08-09 01:50:06

标签: javascript node.js reactjs axios

我有很多客户,并且地址端点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返回地址数组 如果我们得到一个空数组作为响应,那么我们需要从“ customerArray”中添加该ID

 // 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);
    });

});

请帮助我修复它

1 个答案:

答案 0 :(得分:0)

我认为您不知道如何获取最终数据。基本上,您应该将诺言放入一个数组中,然后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);
  });