Javascript Tricky Questions — Promises
1. Can we use await only with promises?
No, we can use await with promise as well as any object that implements a then function.
2. Guess the output
Answer:
Some error occurred
Some error occurred
3. How can I write a sleep function using a promise?
4. Guess the output
Answer:
Error 1
Success 4
5. Guess the output
Answer:
success
error
Error caught
6. Guess the output
Answer:
success
Defeat
error
Error caught
Success: test
7. Guess the output
Answer:
Resolving 500
Resolving 1000
Resolving 1500
Resolving 2000
All done
done 1000
done 2000
done 500
done 1500
8. Guess the output
Answer:
error p4
9. Guess the output
Answer:
p1
p2
p3
undefined
p5
10. Guess the output
Answer:
success 100
11. Guess the output
Answer:
2
4
undefined
8
12. Guess the output
Answer:
start
1
end
13. Guess the output
Answer:
start
1
end
2
14. Guess the output
Answer:
start
1
3
end
2
15. Guess the output
Answer:
start
1
end
The resolve method has never been called, so promise1 is always in the pending state.So promise1.then(…) has never been executed. 2 is not printed out in the console.
16. Guess the output
Answer:
start
middle
1
end
success
Execute synchronous code first, then asynchronous code.
Synchronous code is executed in the order in which it was called.
17. Guess the output
Answer:
start
end
1
2
18. Guess the output
Answer:
start
end
resolve
setTimeout
Tasks with higher priority are called microtasks.
Includes: Promise, ObjectObserver, MutationObserver, process.nextTick, async / await.
Tasks with lower priority are called macrotasks.
Includes: setTimeout, setInterval and XHR.
Order of execution:
- synchronous
- microtasks — promise
- macrotasks — settimeout
19. Guess the output
Answer:
1
2
4
timeStart
timeEnd
success
20. Guess the output
Answer:
timer1
promise1
timer2
21. Guess the output
Answer:
start
end
promise1
timer1
promise2
timer2
23. Guess the output
Answer:
1, 5, 2 ,2, 4
24. Guess the output
Answer:
JS
25. Guess the output
Answer:
1, 8, 7, 7, 7, 2,3 , 4,6,4,6,4,6,5,5,5
26. Guess the output
Answer:
After resolve/reject
2
27. Guess the output
Answer:
2, 5, 1, 1, 4