-
function delay(ms) {
return new Promise(resolve => {
setTimeout(() => {
resolve(new Date())
}, ms)
})
}
async function playingWithDelay() {
console.log('Delaying...', new Date())
const dateAfterOneSecond = await delay(1000)
console.log(dateAfterOneSecond)
const dateAfterThreeSeconds = await delay(3000)
console.log(dateAfterThreeSeconds)
return "done"
}
playingWithDelay()
.then(result => {
console.log(`After 4 seconds: ${result}`)
}) i'm playing with simple code above. it didn't register a callback, so after unwinding the stack, how could it return to the original code context after the asynchronous operation( |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
I'm giving it a try to explain what I think occurs. I'm very happy if anyone can point out errors in my answer or improve it 🙏 The function playingWithDelay() {
console.log('Delaying...', new Date())
return delay(1000).then(dateAfterOneSecond => {
console.log(dateAfterOneSecond)
return delay(3000).then(dateAfterThreeSeconds => {
console.log(dateAfterThreeSeconds)
return "done";
});
})
} Now it should be more clear how it works. You are registering a callback every time you use |
Beta Was this translation helpful? Give feedback.
I'm giving it a try to explain what I think occurs. I'm very happy if anyone can point out errors in my answer or improve it 🙏
The
async/await
syntax is syntactic sugar for Promises. HenceplayingWithDelay
can be rewritten as:Now it should be more clear how it works. You are registering a callback every time you use
await
.