I can’t understand why I am getting the error in the subject:
var a = async function(){
await setTimeout(function(){console.log('Hi');},2000);
return(7);
}.then((res)=>{console.log(res);});
console.log(a());
It’s just a test to learn to work with async/await and promises, my code shouldn’t do anything meaningful
2
Answers
You should call
.then
on aPromise
to get the result after it completes. Currently, you are attempting to call.then
on afunction
, which does not have this method. You would need to call the async function to get aPromise
, which you can then wait for.For example:
Note that
await
does not make sense withsetTimeout
, as it does not return aPromise
.You can use this as a sample for trying out
async/await
withPromises
Few points to note:
await
onlyPromises
,setTimeout
does not createPromises
rather it is used to imitate a time taking process.async
function always returnPromises
.