Skip to content

Instantly share code, notes, and snippets.

@memodoring
Last active November 1, 2018 05:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save memodoring/ad62bb3da0b0c434fb85042085b96c6b to your computer and use it in GitHub Desktop.
Save memodoring/ad62bb3da0b0c434fb85042085b96c6b to your computer and use it in GitHub Desktop.
Async https call
async function httpRequestPromise(options) {
//log the options in case we need to debug
console.log(`~~~~~~~~~~~~~~~${JSON.stringify(options)}~~~~~~~~~~~~~`);
// return new pending promise
return new Promise((resolve, reject) => {
const request = http.request(options, (response) => {
// reject the promise if the HTTP status isn't `Successful 2xx`
if (response.statusCode < 200 || response.statusCode > 299) {
reject(new Error('Failed to load page, status code: ' + response.statusCode));
}
// crete an array for holding data temporarily
const body = [];
// every time we get data, grab the chunk and push it to the array
response.on('data', (chunk) => body.push(chunk));
// when we are done, resolve the promise with all the chunks joined
response.on('end', () => resolve(body.join('')));
});
// reject the promise if there are connection errors of the request
request.on('error', (err) => reject(err));
request.end();
});
}
@tryingtokeepup
Copy link

thank you for the code!

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