This problem was asked by Amazon.
What does the code snippet to the right output by console.log?
console.log(1)
const promise = new Promise((resolve) => {
console.log(2)
resolve()
console.log(3)
})
console.log(4)
promise.then(() => {
console.log(5)
}).then(() => {
console.log(6)
})
console.log(7)
setTimeout(() => {
console.log(8)
}, 10)
setTimeout(() => {
console.log(9)
}, 0)
output
1
2
3
4
7
5
6
9
8
Explanation
- The synchronous code runs first. So 1, 2, 3, 4 , 7 are logged immediately.
- 5 and 6 are logged after 7 since they are in .then() handlers.
- 9 is logged before 8 since the timeout of 0 ms happens sooner than 10 ms.
- Promises and timeout callbacks are asynchronous which is why they run after the sync code.
Top comments (0)