简体   繁体   English

如何提出多个请求?

[英]How to make multiple requests?

I have an array of data and need to fetch data for each item and combine them.我有一个数据数组,需要为每个项目获取数据并将它们组合起来。

// This is inside a Nextjs async API route

const data = ['item1','item2','item3']

let result = []

data.forEach(async (item)=>{
const res = await fetch(`https://websitename.com/${item}`)
result = [...result,...res]
}

console.log(result)  //gives an empty array

Here, it returns an empty array even though for each item data is being fetched.在这里,即使正在获取每个项目的数据,它也会返回一个空数组。 How to make such requests?如何提出这样的要求?

} }

Your code should be throwing errors I think?我认为您的代码应该抛出错误? You're trying to declare result twice, but as the second time is within the forEach loop, it's actually a different variable, and is created and destroyed for each loop.您试图两次声明结果,但由于第二次在 forEach 循环内,它实际上是一个不同的变量,并且为每个循环创建和销毁。

Assuming your fetch works, this should work:假设您的 fetch 有效,这应该有效:

const data = ['item1','item2','item3']

let result = []

data.forEach(async (item)=>{
const res = await fetch(`https://websitename.com/${item}`)
result = [...result,...res]
}

console.log(result)

May this could help you:)希望这可以帮助你:)

async function doRequest(data) {
   // process here
}

const requests = ['item1', 'item2', 'item3'];
const results = requests.map(async (val) => {
    const response = await doRequest();
    return response;
});

await Promise.all(requests);

Change:改变:

const res = await fetch(`https://websitename.com/${item}`)
const result = [...result,...res]

To:至:

const response = await fetch(`https://websitename.com/${item}`);
const data = response.json(); // if your response is Json
result.push(data);
  • result should be const instead of let结果应该是const而不是let

Method.forEach() makes sync iteration. Method.forEach() 进行同步迭代。 It means that an iteration does not wait resolving of your async callback, but just starts it.这意味着迭代不会等待异步回调的解决,而只是启动它。 As a result forEach starts all requests and jumps to line with console.log(result).结果 forEach 启动所有请求并跳转到 console.log(result)。 But at the moment none of the requests are done and array is still empty.但目前没有任何请求完成,数组仍然为空。 If you wrap like that s etTimeout(()=>console.log(result),3000) you will see that the array is filled with data.如果你像这样包装 s etTimeout(()=>console.log(result),3000)你会看到这个数组被数据填充了。

If you want to make sequential calls:如果要进行顺序调用:

(async function() {
  const data = ['item1','item2','item3']
  let result = []
  for await (const item of data) {
    const res = await fetch(`https://websitename.com/${item}`)
    console.log(item);
    result.push(item)
  }
  console.log(result)
})();

If you want to make parallel calls:如果要进行并行调用:

(async function() {
const data = ['item1','item2','item3']
let result = await Promise.all(data.map(async (item)=>{
return await await fetch(`https://websitename.com/${item}`)
}))

console.log(result)
})();

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

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