Created
April 6, 2017 07:22
-
-
Save allex/03949e7ce81b740adba9fd31aff9b7c2 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
| /** | |
| * Convert a promise to a stream instance. | |
| * | |
| * @author Allex Wang ([email protected]) | |
| * | |
| * MIT Licensed | |
| * | |
| * GistID: 03949e7ce81b740adba9fd31aff9b7c2 | |
| * GistURL: https://gist.github.com/03949e7ce81b740adba9fd31aff9b7c2 | |
| */ | |
| 'use strict'; | |
| var Readable = require('stream').Readable; | |
| class Streamify extends Readable { | |
| constructor(promise, options) { | |
| super(options); | |
| this.__promise = promise; | |
| this.__resolvingPromise = false; | |
| } | |
| _read() { | |
| var self = this; | |
| if (!self.__resolvingPromise) { | |
| self.__resolvingPromise = true; | |
| self.__promise.then( | |
| value => { | |
| if (value && typeof value !== 'string') { | |
| value = typeof value === 'object' ? JSON.stringify(value) : value.toString(); | |
| } | |
| self.push(value); | |
| self.push(null); | |
| }, | |
| error => { | |
| self.emit('error', error); | |
| self.push(null); | |
| } | |
| ); | |
| } | |
| }; | |
| } | |
| module.exports = (promise, options) => new Streamify(promise, options) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment