繁体   English   中英

通过 reactjs 中的不同 id 从 api 获取数据

[英]fetch data from api by different ids in reactjs

我有一个 ID 列表,即:[3,6,7] 我想从 api 中获取 ID 为 3,6 和 7 的所有对象。 我只能用一个 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 获取? 提前致谢。

您可以使用Promise.all https://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)

fetch(...)返回一个 promise。

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

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

const p1 = fetch(...)
const p2 = fetch(...)
const p3 = fetch(...)

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM