【问题标题】:fetch data from api by different ids in reactjs在 reactjs 中通过不同的 id 从 api 获取数据
【发布时间】:2019-10-29 18:02:45
【问题描述】:

我有一个 ID 列表,即:[3,6,7] 我想从 api 中获取所有具有 3,6 和 7 作为 id 的对象。 我只能用一个 ID 来获取它。像这样:

 const response = await fetch(`http://localhost:3000/api`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json; charset=utf-8',
    },
    body: JSON.stringify({
      id: 7,
    }),
  });

如何获取不同的 ID? 提前致谢。

【问题讨论】:

  • 使用response = await Promise.all([fetch(...id1), fetch(...id2), fetch(...id3)])

标签: javascript node.js reactjs postgresql fetch


【解决方案1】:

你可以使用Promise.allhttps://developer.mozilla.org/vi/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

const promises = [3,6,7].map(id => {
  return fetch(`http://localhost:3000/api`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json; charset=utf-8',
    },
    body: JSON.stringify({
      id,
    }),
  })
})

const response = await Promise.all(promies)
console.log(responese)

【讨论】:

    【解决方案2】:

    fetch(...) 返回一个承诺。

    await fetch(...) 获取返回的承诺的结果。

    因此,要一次进行多个调用,您需要处理多个 Promise。

    const p1 = fetch(...)
    const p2 = fetch(...)
    const p3 = fetch(...)
    
    const [p1Result, p2Result, p3Result] = await Promise.all(p1, p2, p3);
    

    将这些 fetcher 的结果放在 Result consts 中。

    【讨论】:

      【解决方案3】:

      最好将你的请求放在一个数组中并等待它们完成。

      const myLogic = () => {
          //Put ids in function and get responses
          getByIds([3,6,7]).then(responses => {
              console.log(responses);        
          });
      }
      
      const getByIds = async (ids) => {
          //put all promises in an Array so we can let them run and be awaited
          //await is bad practise in loops and usually does not work
          let requests = [];
          let responses = [];
      
          for (let id in ids)
              requests.push(fetch(`http://localhost:3000/api`, {
                  method: 'POST',
                  body: JSON.stringify({ id }),
                  headers: { 'Content-Type': 'application/json; charset=utf-8' },
              })
                  //Add response to array
                  .then(response => responses.push(response))
                  .catch(err => console.log(err)));
      
          //Await all requests
          await Promise.all(requests);
      
          //return all responses
          return responses;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-05-16
        • 2020-06-04
        • 2020-11-19
        • 2021-01-03
        • 2018-06-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多