await is only valid in async function error for a async function [duplicate]

喜夏-厌秋 提交于 2021-01-28 05:03:29

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/62358874/await-is-only-valid-in-async-function-error-for-a-async-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!