Skip to content

Instantly share code, notes, and snippets.

@jasnell
Last active February 25, 2020 21:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasnell/39aa71e98f9648e6cf41c4596df1e71c to your computer and use it in GitHub Desktop.
Save jasnell/39aa71e98f9648e6cf41c4596df1e71c to your computer and use it in GitHub Desktop.
Promises example
const { createHook } = require('async_hooks');
const { promisify } = require('util');
const sleep = promisify(setTimeout);
let count = 0;
const hook = createHook({
init(id, type) {
if (type === 'PROMISE')
count++;
}
});
hook.enable();
async function foo() {
await sleep(10);
// return Promise.resolve(5);
return 5;
}
foo().then(console.log);
process.on('exit', () => console.log(count));
const { createHook } = require('async_hooks');
const { promisify } = require('util');
let count = 0;
let resolves = 0;
let callbacks = 0;
const set = new Set();
const hook = createHook({
init(id, type) {
if (type === 'PROMISE') {
set.add(id);
count++;
}
},
after(id) {
if (set.has(id))
callbacks++;
},
promiseResolve() {
resolves++;
}
});
hook.enable();
function foo() {
//async function foo() {
return new Promise((res, rej) => {
setTimeout(() => res(5), 10);
});
}
foo().then(console.log);
process.on('exit', () => console.log(count, resolves, callbacks));
const { createServer } = require('http');
const { createHook } = require('async_hooks');
const { promisify } = require('util');
let count = 0;
const set = new Set();
const hook = createHook({
init(id, type) {
if (type === 'PROMISE') {
set.add(id);
count++;
}
}
});
hook.enable();
createServer((req, res) => {
foo()
.then((d) => res.end(`${d}`))
.catch(console.log);
}).listen(8000);
//async function foo() {
function foo() {
return new Promise((res, rej) => {
setTimeout(() => {
res(count);
}, 10);
});
}
// function foo() == 6k requests = 18897 Promises
// async function foo() == 6k requests = 31535 Promises
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment