Applying a timeout in AWS Lambda with node.js
Sometimes a calling a external service or executing a block can may take too long to resolve or reject, and most of times you don't wait for it.
So using Promise.race we can handle it. Next code shows how.
// timeoutPromise
module.exports = {
timeoutPromise: function (ms, step, promise) {
// Create a promise that rejects in <ms> milliseconds
let timeout = new Promise((resolve, reject) => {
let id = setTimeout(() => {
clearTimeout(id);
reject(`Timed out in step: ${step}`);
}, ms)
})
// Returns a race between our timeout and the passed in promise
return Promise.race([
promise,
timeout
])
}
}
// index.js (the lambda)
const util = require('./timeoutPromise');
exports.handler = async (event, context) => {
try{
// Create a promise that rejects in <ms> milliseconds
const doSomething = function() {
return new Promise((resolve, reject) => {
setTimeout(() => resolve('AsyncFunction excecuted on time'), 2000)
})
};
// Apply a timeout of 3 seconds to doSomething
let doIt = await util.timeoutPromise(3000, 'doSomething step', doSomething())
return { body: JSON.stringify(doIt) }
} catch (error) {
// Deal with error
context.fail(error)
}
};