await仅在异步功能错误中对异步功能有效

时间:2020-06-13 11:07:22

标签: javascript node.js express fetch

我使用 全部承诺 同时获取2个URL,但是当我使用await调用此函数时(因为getAllURLs是异步函数),这给了我一个错误, 我怎么解决这个问题?

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)

错误:

 let responses = await getAllUrls(urls)

 await is only valid in async function

1 个答案:

答案 0 :(得分:2)

您只能在await函数内调用async,例如:

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

或者,您可以使用具有顶级await支持的JS引擎或编译器。

相关问题