2

I am fetching 2 URLs at the same time using Promise all but when I am calling this function using await (as getAllURLs is async function) it gives me an error, How can I solve this problem?

const fetch = require("node-fetch");

let urls = ["https://jsonplaceholder.typicode.com/users","https://jsonplaceholder.typicode.com/users"]

async function getAllUrls(urls) {
  try {
    var data = await Promise.all(
      urls.map((url) => fetch(url).then((response) => response.json()))
    );

    return data;

  } catch (error) {
    console.log(error);

    throw error;
  }
}


const response = await getAllUrls(urls) 
console.log(response)

Error :

 let responses = await getAllUrls(urls)

 await is only valid in async function
KaranManral
  • 644
  • 4
  • 13

1 Answers1

2

You can only call await inside an async function, for example:

(async () => {
  const response = await getAllUrls(urls) 
  console.log(response)
)()

Alternatively, you can use a JS engine or compiler with top-level await support.

Nick McCurdy
  • 17,658
  • 5
  • 50
  • 82