I have a web page which content is as simple as:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="" xml:lang="">
<head>
<script>
async function download() {
const action = async () => {
const response = await fetch("https://www.example.com/json", {
method: "GET"
});
const data = await response.json();
return data;
}
return action();
}
const result = await download();
// do something with `result` here
</script>
</head>
<body>
...
</body>
</html>
The point with the above code is that it produces the following error: Uncaught SyntaxError: await is only valid in async functions, async generators and modules
.
As I understand the point of this error I tried to change it to use Promise
.. without success:
async function download() {
const action = async () => {
const response = await fetch("https://www.example.com/json", {
method: "GET"
});
const data = await response.json();
return data;
}
return action();
}
const p = new Promise(() => download());
const results = Promise.all([p]);
const result = results[0];
// do something with `result` here
With this code, the Promise
state is still pending
at the time I want to use the result.
NOTE: I know it is a bad practice for user experience to perform blocking operations. In the context of this question, it is the expected behavior.