Last active
May 7, 2018 11:43
-
-
Save rafaelkendrik/c2140b261246d8e92fe3423b389daa6f to your computer and use it in GitHub Desktop.
Non-blocking, callback and pomises on Javascript's event loop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* X example - common non-blocking execution */ | |
const x = 5 | |
console.log('hello X', x) | |
const plusOneX = (x) => { | |
setTimeout(() => { | |
// a bad reassign e.g.: | |
x = x + 1 | |
console.log('new X', x) | |
}, 5000) | |
} | |
plusOneX(x) | |
console.log('bye X', x) | |
// results: | |
// hello X 5 | |
// bye X 5 | |
// new X 6 | |
/* Y example - callback exection */ | |
const y = 5 | |
console.log('hello Y', y) | |
const plusOneY = (y, cb) => { | |
setTimeout(() => { | |
const ny = y + 1 | |
console.log('new Y', ny) | |
cb(ny) | |
}, 5000) | |
} | |
plusOneY(y, (ny) => { | |
console.log('bye Y', ny) | |
}) | |
// results: | |
// hello Y 5 | |
// new Y 6 | |
// bye Y 6 | |
/* Z example - promise execution */ | |
const z = 5 | |
console.log('hello Z', z) | |
const plusOneZ = (z) => | |
new Promise((resolve, reject) => { | |
setTimeout(() => { | |
const nz = z + 1 | |
console.log('new Z', nz) | |
resolve(nz) | |
}, 5000) | |
}) | |
plusOneZ(z).then((nz) => { | |
console.log('bye Z', nz) | |
}) | |
// results: | |
// hello Z 5 | |
// new Z 6 | |
// bye Z 6 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
example X:
Common non-blocking execution,
x
is only incremented after the timeout execution, but 'bye' is printed before it.example Y:
The callback function contains the print of 'bye', that was passed to the queue and returns to the stack after timeout execution.
example Z:
As callback, 'bye' printed after the promise resolve.
Javascript's Event Loop Introduction: