我正在使用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
您只能在async
函数中调用await
,例如:
(async () => {
const response = await getAllUrls(urls)
console.log(response)
)()
或者,您可以使用具有顶级await
支持的JS引擎或编译器。