Last active
November 1, 2018 05:47
-
-
Save memodoring/ad62bb3da0b0c434fb85042085b96c6b to your computer and use it in GitHub Desktop.
Async https call
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thank you for the code!