Skip to content

Instantly share code, notes, and snippets.

@evanlucas
Created April 28, 2022 13:53
Show Gist options
  • Save evanlucas/f876377593138d557e866c93ff103c23 to your computer and use it in GitHub Desktop.
Save evanlucas/f876377593138d557e866c93ff103c23 to your computer and use it in GitHub Desktop.
tap test with async_hooks abort
'use strict'
const {EventEmitter, once} = require('events')
const fs = require('fs/promises')
const {
setImmediate: defer
, setTimeout: sleep
} = require('timers/promises')
const tap = require('tap')
class Biscuits {
constructor() {
this.emitter = new EventEmitter()
this.is_running = false
this.ac = new AbortController()
this.flush_interval_ms = 250
}
async start() {
if (this.is_running) return
this.is_running = true
while (this.is_running) {
try {
await sleep(this.flush_interval_ms, null, {
signal: this.ac.signal
})
} catch (err) {
if (err.name !== 'AbortError') throw err
this.is_running = false
}
await this.flush()
await defer()
}
// Replacing the next line with this.emitter.emit('done')
// for it to be correct. This triggers the bug.
this.emit('done')
}
async close() {
if (!this.is_running) return
const done = once(this.emitter, 'done')
this.is_running = false
await done
console.log('done')
}
async flush() {
return fs.readFile(__filename)
}
async closeDB() {
await this.flush()
await sleep(250)
}
}
tap.test('biscuits', async (t) => {
t.test('subbiscuits', async (t) => {
const a = new Biscuits()
a.start()
await sleep(500)
await a.closeDB()
await sleep(250)
await a.close()
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment