0

I'm trying to make a bunch of request an await to all of them to be completed with a Promise.all() function, but instead of doing manually all the fetchs like this:

var data = await Promise.all([
        fetch('https://jsonplaceholder.typicode.com/posts').then((response) => response.json()),
        fetch('https://jsonplaceholder.typicode.com/albums').then((response) => response.json()),
        fetch('https://jsonplaceholder.typicode.com/users').then((response) => response.json())
      ]);

i want to make it dynamic, to make N fetch requests like this:

       let promiseList = [];
        try {
            for (let url of requestUrls) {
                promiseList.push(fetch(url).then((response) => response.json()));
            }

            var data = await Promise.all(promiseList);

But i get this error Uncaught SyntaxError: await is only valid in async function in the await Promise.all() line, if i delete the await, i get a Promise {<pending>} and (index):79 error:TypeError: data is not iterable

This is my full code: https://jsfiddle.net/ham7g82e/1/

What i'm missing to get the data from those fetchs?

Progs
  • 1,059
  • 7
  • 27
  • 63

3 Answers3

2

To use await, it needs to be part of an async function.

async function functionName() {
 //You can use await in here, because you used the async keyword
}
Ali Ann
  • 169
  • 5
2

Don't use await, instead use Promise.then

Promise.all(promiseList).then(data => {
  document.getElementById("result").innerHTML = data;
  console.log(data);

  for (var i of data) {
    console.log(`RESPONSE ITEM \n`);
      for (var obj of i) {
        console.log(obj);

      }
  }
});
WilliamNHarvey
  • 2,335
  • 2
  • 17
  • 26
0

If the function where are executing this code is not async, you could just use the .then() to get the values from the promises. There is not need to use await.

Check this documentation: Promise.all()

Paul Bota
  • 141
  • 9