Created
December 4, 2019 16:49
-
-
Save dy/8ca154c96e2b2a823c6501d29972b8a8 to your computer and use it in GitHub Desktop.
Readable stream async iterator polyfill
This file contains 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
// 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