Created
April 24, 2018 17:03
-
-
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
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
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