0

let kunas = document.querySelector(`body`);


let spalvaLaik = async (spalv,laik) => setTimeout(() => {
    kunas.style.backgroundColor = spalv;
}, laik);  



await spalvaLaik("blue",1000)
await spalvaLaik("green",1000)
await spalvaLaik("yellow",1000)
<!DOCTYPE html>
<html>
<head>
    <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">

    <title></title>
</head>
<body>
<p>para</p>
<script type="text/javascript" src="script.js"></script> 
</body>
</html>

Hi I'm trying to make the await work but it keeps showing this error : Uncaught SyntaxError: await is only valid in async functions, async generators and modules ;

Is there something wrong here? Because Im pretty sure I declared the arrow function to be an async one. I tried other suggestions but none seems to work. Any help is appreciated. Thanks!

edga9966
  • 77
  • 1
  • 2
  • 8
  • 1
    The `await` statements aren't inside the arrow function that's declared `async`. – Barmar Aug 23 '21 at 18:34
  • 1
    Note that `setTimeout()` doesn't wait for the callback function to run, so declaring the caller to be `async` doesn't mean that `await` will wait for the timeout. – Barmar Aug 23 '21 at 18:35
  • 1
    `await` needs to be inside an `async` function. Also, awaiting those "async" functions isn't going to work because they don't return promises. – Nick Aug 23 '21 at 18:35
  • Your `await` is not directly _in_ an async function or a module. You could change `type="text/javascript"` to `type="module"`, but the way you’re using `setTimeout` as a Promise doesn’t seem correct. – Sebastian Simon Aug 23 '21 at 18:35
  • 2
    See https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep for how to write a `sleep()` function in JavaScript using promises. – Barmar Aug 23 '21 at 18:36

0 Answers0