Skip to content

Instantly share code, notes, and snippets.

@talawahtech
Created April 24, 2018 17:03
Show Gist options
  • Save talawahtech/f8c4452dbb543297a008d3856ef47adb to your computer and use it in GitHub Desktop.
Save talawahtech/f8c4452dbb543297a008d3856ef47adb to your computer and use it in GitHub Desktop.
Example Lambda function that wraps https.request in a promise so it can be used with async/await
const https = require('https');
exports.handler = async (event) => {
const response = await asyncHttpRequest({ hostname: 'httpbin.org', path: '/ip' });
return JSON.parse(response);
};
function asyncHttpRequest(params, postData) {
return new Promise(function(resolve, reject) {
const req = https.request(params, function(res) {
// reject on bad status
if (res.statusCode < 200 || res.statusCode >= 300) {
return reject(new Error(`statusCode=${res.statusCode} path=${params.path}`));
}
let body = '';
res.on('data', (chunk) => body += chunk);
res.on('end', () => resolve(body));
});
req.on('error', (err) => reject(err));
if (postData) { req.write(postData) }
req.end();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment