-
-
Save jasnell/39aa71e98f9648e6cf41c4596df1e71c to your computer and use it in GitHub Desktop.
Promises example
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 { 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)); |
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 { 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)); |
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 { 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