I am new to JS and I am writing some simple REST API in Node.js for my application. Somewhere inside the code I want to wait for about 5 seconds.
I am so confused about using of Promise and normal timeout method and call the function somewhere else. as following:
const sleep = (time) => {
return new Promise(resolve => {
setTimeout(() => {
resolve()
console.log('5 seconds');
}, time);
})
}
and then call the function:
sleep(5000)
OR
const sleep = (time) => {
return new Promise(resolve => {
setTimeout(() => {
resolve()
console.log('5 seconds');
}, time);
})
}
and then call the function:
sleep(5000).then(() => console.log('5 seconds passed'))
OR
const sleep = (time) => {
return new Promise(resolve => {
setTimeout(() => {
resolve()
console.log('5 seconds');
}, time);
})
}
async function wait(sleepTime) {
await sleep(sleepTime)
}
and then call the function:
wait(5000)
Am I doing something wrong? Because in all 3 cases I actually get a waiting time of 5 seconds but since the function returns Promise, I have to use .then()
If I want to use the Promise.