Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // PROGRAM SET UP
- // Blocking code
- function sleep(miliseconds) {
- var start = new Date().getTime();
- var expire = start + miliseconds
- while(new Date().getTime() < expire) {
- }
- }
- // Timeout function to simulate actual ASYNC function that is wrapped in promise
- function timeoutPromise() {
- return new Promise(function(resolve, reject) {
- setTimeout(function() {
- resolve()
- }, 0)
- })
- }
- // Program execution
- console.log('Main context start')
- asyncOperation()
- .then(() => {
- console.log('asyncOperation end')
- })
- console.log('Main context end')
- // Different scenarios for asyncOperation()
- // ============== CASE 1 ============== //
- async function asyncOperation() {
- timeoutPromise()
- sleep(5000)
- console.log('sleep completed')
- }
- // RESULT:
- // 'Main context start'
- // AFTER 5 SECONDS
- // 'sleep completed'
- // 'asyncOperation end'
- // 'Main context end'
- // Blocking code runs immediately after asyncOperation() is invoked, and blocks main context
- // ============== CASE 2 ============== //
- async function asyncOperation() {
- await timeoutPromise()
- sleep(5000)
- console.log('sleep completed')
- }
- // RESULT:
- // 'Main context start'
- // 'Main context end'
- // AFTER 5 SECONDS
- // 'sleep completed'
- // 'asyncOperation end'
- // Main context triggers asyncOperation(), does not wait, and proceeds to print 'main context end'
- // Blocking code runs AFTER timeoutPromise() is completed (and so does not affect main context)
- // Blocking code blocks asyncOperation(). asyncOperation() completes after sleeping 5 seconds
- // Note:
- await timeoutPromise()
- sleep(5000)
- console.log('sleep completed')
- // is identical to
- timeoutPromise().then(function() {
- sleep(5000)
- console.log('sleep completed')
- })
- // ============== CASE 3 ============== //
- async function asyncOperation() {
- timeoutPromise()
- process.nextTick(function() {
- sleep(5000)
- console.log('sleep completed')
- })
- }
- // RESULT:
- // 'Main context start'
- // 'Main context end'
- // AFTER 5 SECONDS
- // 'sleep completed'
- // 'asyncOperation end'
- // Similar to CASE 1, but blocking code execution is deferred to next tick, and does not block main context
- // ============== CASE 4 ============== //
- async function asyncOperation() {
- await timeoutPromise()
- process.nextTick(function() {
- sleep(5000)
- console.log('sleep completed')
- })
- }
- // RESULT:
- // 'Main context start'
- // 'Main context end'
- // 'asyncOperation end'
- // AFTER 5 SECONDS
- // 'sleep completed'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement