【问题标题】:await is only valid in async function error for a async function [duplicate]await 仅在异步函数的异步函数错误中有效[重复]
【发布时间】:2020-10-03 03:11:05
【问题描述】:

我使用 Promise all 同时获取 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

【问题讨论】:

标签: javascript node.js express fetch


【解决方案1】:

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

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

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

【讨论】:

  • 当我使用上述代码时,我得到 [AsyncFunction] 作为输出
  • 输出什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-06-18
  • 2020-09-07
  • 2019-09-12
  • 1970-01-01
  • 2020-08-13
  • 2020-04-15
  • 2020-12-23
相关资源
最近更新 更多