Skip to content

Instantly share code, notes, and snippets.

@dy
Created December 4, 2019 16:49
Show Gist options
  • Save dy/8ca154c96e2b2a823c6501d29972b8a8 to your computer and use it in GitHub Desktop.
Save dy/8ca154c96e2b2a823c6501d29972b8a8 to your computer and use it in GitHub Desktop.
Readable stream async iterator polyfill
// polyfill readable stream iterator
export const ReadableStream = window.ReadableStream && window.ReadableStream.prototype[Symbol.asyncIterator] ?
window.ReadableStream : (() => {
function ReadableStream (...args) {
let readers = []
let obj = args[0]
let stream = new window.ReadableStream(...args)
// patch cancel to release lock
let _cancel = stream.cancel
stream.cancel = function cancel(...args) {
readers.forEach(reader => {
reader.cancel()
reader.releaseLock()
})
readers.length = 0
_cancel.call(this, ...args)
}
stream[Symbol.asyncIterator] =
stream.getIterator = function () {
const reader = stream.getReader()
readers.push(reader)
return {
next() {
return reader.read()
},
return() {
readers.splice(readers.indexOf(reader), 1)
reader.releaseLock()
return {}
},
[Symbol.asyncIterator]() {
return this
}
};
}
return stream
}
return ReadableStream
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment