You will get undefined been logged at once.
It's clear that you are trying to write a sleep()
async function, but do remember that setTimeout is a sync function calling with a callback function will be executed at a given time, so while you are executing test()
, the calling will run to end and return undefined
as you have no return statement in the function body, which will be passed to your .then()
function.
The right way to do this is to return a Promise that will be resolved after a given time, that will continue the then
call.
async function sleep(time){
return new Promise((resolve,reject) => {
setTimeout(() => {
resolve("echo str")
},time)
})
}
sleep(5000).then((echo) => console.log(echo))
sleep function in short
const sleep = async time => new Promise(resolve=>setTimout(resolve,time))