Skip to content
Advertisement

How to use ES8 async/await with streams?

In https://stackoverflow.com/a/18658613/779159 is an example of how to calculate the md5 of a file using the built-in crypto library and streams.

JavaScript

But is it possible to convert this to using ES8 async/await instead of using the callback as seen above, but while still keeping the efficiency of using streams?

Advertisement

Answer

The await keyword only works on promises, not on streams. There are ideas to make an extra stream-like data type that would get its own syntax, but those are highly experimental if at all and I won’t go into details.

Anyway, your callback is only waiting for the end of the stream, which is a perfect fit for a promise. You’d just have to wrap the stream:

JavaScript

There also exists a helper function to do just that in more recent versions of nodejs – pipeline from the stream/promises module:

JavaScript

Now you can await that promise:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement