Skip to content

Instantly share code, notes, and snippets.

@allex
Created April 6, 2017 07:22
Show Gist options
  • Select an option

  • Save allex/03949e7ce81b740adba9fd31aff9b7c2 to your computer and use it in GitHub Desktop.

Select an option

Save allex/03949e7ce81b740adba9fd31aff9b7c2 to your computer and use it in GitHub Desktop.
/**
* 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