3

I have a function that returns a stream and I want to pipe that value to another function then return it in an Express response like so:

const { Duplex } = require('stream');
const request = require('request');

const example = async function getRequest() {
  return request({ blah }).pipe(Duplex);
};

const secondExample = async function getRequestSecond() {
  return example().pipe(Duplex);
};

router.get('/', async (req, res) => {
  return secondExample().pipe(res);
});

These functions all sit in different classes, but the general idea is the same. My understanding of Streams leads me to believe that piping the data to a Duplex stream and returning that should allow me to pipe it all the way down to the response, but at the secondExmaple function and in the router.get function I start to get TypeError: secondExample(...).pipe is not a function and I'm not understanding why.

Stretch0
  • 8,362
  • 13
  • 71
  • 133
loganhuskins
  • 1,399
  • 3
  • 15
  • 33
  • Why did you mark those functions with `async`? This makes a function to always return a Promise which has no `pipe` method. – Yury Tarabanko Jan 18 '18 at 22:46
  • Because in my actual application those functions do perform some asynchronous stuff that has to be awaited. I was awaiting the functions but my linter yelled at me for awaiting in a return statement. The ```request``` function should be awaited either way. – loganhuskins Jan 18 '18 at 22:55
  • if you use Promises, use `.then` to access the resolved value – Jaromanda X Jan 18 '18 at 22:56
  • But I can also await them, which will allow me to access the resolved value, correct? Even with the resolved value accessed by awaiting I get that error. – loganhuskins Jan 18 '18 at 22:59
  • You can't await streams. Only thenable objects. And if you have async function that resolves with a stream you need to use await before calling `pipe` on it `(await secondExample()).pipe(res)` – Yury Tarabanko Jan 18 '18 at 23:02
  • So, for example, if I was using the request-promise library I would ```return (await request({})).pipe(Duplex);```. Then I'd await that function in the same manner and so on and so on. When I do that I get another error ```TypeError: (intermediate value).pipe is not a function```. – loganhuskins Jan 19 '18 at 15:59
  • this.usersForm .get('userInput') .valueChanges.subscribe(value => { this.isLoading = true; if (value !== "") { console.log(value) this.isLoading = false; } }); the loader does not work may be because observable wait for a keyup event to finish ? – de albuquerque frank Sep 14 '20 at 10:40

0 Answers0