Skip to content

Instantly share code, notes, and snippets.

@mdr
Last active September 12, 2018 16:34
Show Gist options
  • Save mdr/13b92123c3e4bf2c81263e9617957745 to your computer and use it in GitHub Desktop.
Save mdr/13b92123c3e4bf2c81263e9617957745 to your computer and use it in GitHub Desktop.
class AsyncSerializer {
constructor() {
this._previousPromise = Promise.resolve(null)
}
serialize = f => {
const newPromise = this._previousPromise.then(() => f())
this._previousPromise = newPromise
return newPromise
}
}
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))
it('no matt no', async () => {
const asyncSerializer = new AsyncSerializer()
let a = 0
asyncSerializer.serialize(async () => {
const aCopy = a
await sleep(1000)
a = aCopy + 1
})
const resultPromise = asyncSerializer.serialize(async () => {
const aCopy = a
await sleep(50)
a = aCopy + 1
})
await resultPromise
expect(resultPromise).toBe(2)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment