How to combine multiple requests response nodejs?

Viewed 46

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}`)
console.log(res)  //gives a valid data
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?

3 Answers

The answer you get is in json format. You must convert it before you can use it

const res = await fetch(`https://websitename.com/${item}`    
    const data = await res.json()
    console.log(data)

If this doesn't solve your problem, then it's probably more of an async thin , JS is not fill the array before you call it

Because you are executing the async function inside the loop where it only returns promise for each execution. In this case, You can use Promise.all()

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

let requests = data.map(item => {
    return fetch(`https://websitename.com/${item}`);
};

Promise.all(requests).then((responses) => {

    // Reason of using flat is, You will get array of responses like [[res1], [res2], [res3]]
    // If you want to merge those together, You can use flat()
    const results = responses.flat();

    // do whatever you want with results

});

Read about using Async/Await in Array methods

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

let result = []

for(var i=0;i<data.length;i++){

    const res = await fetch(`https://websitename.com/${data[i]}`)
    console.log(res)  //gives a valid data
    result = [...result,...res]
}

console.log(result)
Related