Lambda’s Node.js runtimes support JavaScript’s standard implementation of Asynchronous function. This allows function calls to return a “promise”, which is a placeholder for an eventual response. The promise is received immediately, and normal code execution resumes without waiting for the final response. The benefit of this is speed, as non-dependent code can continue executing while a separate processing thread waits to resolve the promise into a full response.
If using a JavaScript library that already supports promises, like the aws-sdk, you can simply append .promise()
method to your call:
const AWS = require('aws-sdk');
const lambda = new AWS.Lambda();
exports.handler = async (event) => lambda.listFunctions().promise();
When dealing with code that does not inherently support promises, a promise can be constructed using the Promise Constructor syntax. Note: you can read more about Promises in my earlier post.
const https = require('https')
let url = "https://docs.aws.amazon.com/lambda/latest/dg/welcome.html"
exports.handler = async function(event) {
const promise = new Promise(function(resolve, reject) {
https.get(url, (res) => {
resolve(res.statusCode)
}).on('error', (e) => {
reject(Error(e))
})
})
return promise
}
The examples above were adapted from the official AWS documentation article on Function Handler in Node.js.