Skip to content

Instantly share code, notes, and snippets.

@krnlde
Last active February 22, 2023 03:42
Show Gist options
  • Star 22 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save krnlde/797e5e0a6f12cc9bd563123756fc101f to your computer and use it in GitHub Desktop.
Save krnlde/797e5e0a6f12cc9bd563123756fc101f to your computer and use it in GitHub Desktop.
util.promisify.custom and http.get example
const http = require('http');
const {promisify} = require('util');
http.get[promisify.custom] = function getAsync(options) {
return new Promise((resolve, reject) => {
http.get(options, (response) => {
response.end = new Promise((resolve) => response.on('end', resolve));
resolve(response);
}).on('error', reject);
});
};
const get = promisify(http.get);
(async () => {
try {
const response = await get('http://krnl.de/');
let body = '';
response.on('data', (chunk) => body += chunk);
await response.end;
console.log(body);
} catch(e) {
// statements
console.log(e);
}
})();
@lagden
Copy link

lagden commented Jun 3, 2020

Nice snippet!
One suggestion.

From:

response.on('data', (chunk) => body += chunk);
await response.end;

To:

for await (const chunk of response) {
  body += chunk
}

@krnlde
Copy link
Author

krnlde commented Jun 5, 2020

Done :)

const http = require('http');
const { promisify } = require('util');

function makeDeferred() {
  let resolve;
  let reject;

  const promise = new Promise((res, rej) => {
    resolve = res;
    reject = rej;
  });

  return {resolve, reject, promise};
}

http.get[promisify.custom] = function getAsync(options) {
  return new Promise((resolve, reject) => {
    http.get(options, (response) => {
      async function* iterator() {
        let ended = false;
        let next = makeDeferred();

        response.on('end', () => ended = true);
        response.on('error', (e) => next.reject(e));
        response.on('data', (chunk) => {
          next.resolve(chunk);
          next = makeDeferred();
        });

        while (!ended) {
          yield await next.promise;
        }
      }

      resolve(iterator());
    }).on('error', reject);
  });
};

/////////////////////////////////////////////

const get = promisify(http.get);

(async () => {
  try {
    const response = await get('http://google.com/');
    let body = '';
    for await (const chunk of response) {
      body += chunk;
    }
    console.log(body);
  } catch(e) {
    // statements
    console.log(e);
  }
})();

@ashen114
Copy link

Nice snippet! One suggestion.

From:

response.on('data', (chunk) => body += chunk);
await response.end;

To:

for await (const chunk of response) {
  body += chunk
}

awesome!!! (╹ڡ╹ )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment