How to Convert a Stream Into a Promise in JavaScript

Many libraries and functions in Node.js and other JavaScript libraries use streaming API to send data. But using streaming API in a browser is painful and if not handled properly, there will be race conditions and random weird behavior.

Let's demonstrate how to do a wrapper around streaming API to get a Promise.

In this example I'll convert a blob object to a binary string in a browser.

function convertBlobToBinaryString(blob) {
  return new Promise((resolve, reject) => {
    const reader = FileReader();

    reader.onload = () => {
      resolve(reader.result);
    }

    reader.onabort = () => {
      reject(new Error('Reading blob aborted'));
    }

    reader.onerror = () => {
      reject(new Error('Error reading blob'));
    }

    reader.readAsBinaryString(blob);
  });
}

  • on line 1 we define a function which accepts a Blob object
  • to read it as a binary string, FileReader API is used, readAsBinaryString function
  • FileReader uses streaming API
  • new Promise takes two parameters in a callback, resolve and reject where resolve finishes a promise successfully and reject finishes it with error.
  • the parameter of resolve() will be returned in a promise which means it will be available in .then() function
  • the parameter of reject() will be available in .catch() and should be an Error object