问题
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