Created
December 5, 2020 19:42
-
-
Save benjamingr/b4e03df6985507cb5343d8f96a50d201 to your computer and use it in GitHub Desktop.
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
'use strict'; | |
const { withToken, token } = require('./token.js'); | |
const { setTimeout } = require('timers/promises'); | |
const controller = withToken(() => { | |
flow(); | |
}); | |
setTimeout(100).then(() => { | |
console.log('aborting'); | |
controller.abort() | |
}); | |
async function flow() { | |
let i = 0; | |
while(!token().aborted) { | |
await setTimeout(20, { signal: token() }); | |
console.log(token()); | |
console.log(i++); | |
} | |
} |
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
'use strict'; | |
const { AsyncLocalStorage } = require('async_hooks'); | |
const store = new AsyncLocalStorage(); | |
module.exports.token = function token() { | |
return store.getStore()?.signal; | |
} | |
module.exports.withToken = function withToken(cb, controller = new AbortController()) { | |
store.run({ signal: controller.signal }, cb); | |
return controller; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment