async-local-storage
async-local-storage copied to clipboard
Is there a reason this won't work on AWS Lambda?
I'm attempting to run this in a Lambda. All works fine locally and on build server from the perspective of unit tests and some functional tests. However when running in Lambda the simplest set/get won't work:
// index.ts
const als = require('async-local-storage');
als.enable();
// ... some code
exports.handler = async (event: APIGatewayEvent, context: APIGatewayEventRequestContext) => {
// some code
als.set('blah', '123');
const blah = als.get('blah');
console.log(`blah ${blah}`);
}
The console above shows blah null instead of blah 123.
I am sorry that I haven't used Lambda before, and I will have a try.
I do a test like this: DEBUG=als node app.js
const als = require('async-local-storage');
als.enable();
// ... some code
exports.handler = async () => {
// some code
als.set('blah', '123');
const blah = als.get('blah');
console.log(`blah ${blah}`);
}
exports.handler();
The logs is as follows:
id:5, type:PROMISE, triggerId:1
5(PROMISE) init by 1
set blah:123 to 1
get blah:null from 1
blah null
id:6, type:TickObject, triggerId:1
6(TickObject) init by 1
destroy 6
The exports.handler function is triggered by 1(id). When the 1(id) is initialized, async-local-storage isn't enabled at that moment; therefor it can't initialize the data scope.
I think AWS Lambda calls the exports.handler function in the same way, you can use like this:
const als = require('async-local-storage');
als.enable();
const handler = async () => {
// some code
als.set('blah', '123');
const blah = als.get('blah');
console.log(`blah ${blah}`);
}
// ... some code
exports.handler = async () => {
setImmediate(handler);
}
exports.handler();