Last active
November 29, 2019 19:18
-
-
Save shqld/acc3144c3261445705338ac463b83be8 to your computer and use it in GitHub Desktop.
Async handling for sync operations on server-side, leveraging EventLoop
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
const express = require('express') | |
const sleep = (ms) => new Promise((res, rej) => setTimeout(res, ms)) | |
const sleepSync = (ms) => { | |
const start = new Date() | |
while (new Date() - start < ms) {} | |
} | |
const server = express() | |
server.get('/heavy/:type', (req, res) => { | |
console.log('heavy: start') | |
const inner = () => { | |
sleepSync(1000) | |
res.send() | |
console.log('heavy: done') | |
} | |
switch (req.params.type) { | |
case 'raw': | |
return inner() | |
case 'setTimeout': | |
return setTimeout(inner, 0) | |
case 'setImmediate': | |
return setImmediate(inner) | |
case 'process.nextTick': | |
return process.nextTick(inner) | |
case 'Promise.resolve': | |
return Promise.resolve().then(inner) | |
} | |
}) | |
server.get('/light/:id', (req, res) => { | |
console.log(`light-${req.params.id}: start`) | |
res.send() | |
console.log(`light-${req.params.id}: done`) | |
}) | |
server.listen(3000, () => console.log('server started')) |
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
const http = require('http') | |
const type = process.argv.slice(2).pop() | |
const main = async () => { | |
http.get('http://localhost:3000/heavy/' + type) | |
http.get('http://localhost:3000/light/1') | |
http.get('http://localhost:3000/light/2') | |
} | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment