Created
May 27, 2016 23:42
-
-
Save kyle-johnson/42db254c199f408e54aada00c3cb10cc to your computer and use it in GitHub Desktop.
Examining how nodejs does blocking / async / promises
This file contains 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
1 | |
2 | |
3 | |
5 | |
Async timeout queued to fire in 3 seconds... | |
BLOCK for 10 seconds... | |
sleep 1 | |
sleep 2 | |
sleep 3 | |
sleep 4 | |
sleep 5 | |
sleep 6 | |
sleep 7 | |
sleep 8 | |
sleep 9 | |
sleep 10 | |
8 | |
4 | |
7 | |
6 |
This file contains 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
function blockingSleep(time) { | |
var stop = new Date().getTime(); | |
while(new Date().getTime() < stop + time) { | |
; | |
} | |
return; | |
} | |
function resolveInSeconds(sec) { | |
return new Promise((resolve) => { | |
setTimeout(() => { resolve(); }, sec * 1000); | |
}); | |
} | |
console.log(1); | |
var x = new Promise((resolve) => { | |
console.log(2); | |
resolve(); | |
}); | |
console.log(3); | |
x.then(() => { console.log(4); }); | |
console.log(5); | |
console.log('Async timeout queued to fire in 3 seconds...'); | |
resolveInSeconds(3).then(() => { console.log(6); }); | |
x.then(() => { console.log(7); }); | |
console.log('BLOCK for 10 seconds...'); | |
for (var i =0; i < 10; i++) { | |
console.log('sleep '+ (i+1)); | |
blockingSleep(1000); | |
} | |
console.log(8); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment