我使用 全部承诺 同时获取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
答案 0 :(得分:2)
您只能在await
函数内调用async
,例如:
(async () => {
const response = await getAllUrls(urls)
console.log(response)
)()
或者,您可以使用具有顶级await
支持的JS引擎或编译器。