I want something like thread-local storage in threaded programming and async_hooks is usable in node.js 8.0, so there is an easy way to use thread-local.
API
constals=require('async-local-storage');
als.enable();
setTimeout(()=>{
als.scope();
constid=randomBytes(8);
als.set('id', id);
delay().then(()=>{
assert.equal(als.get('id'), id);
returnreadfilePromise(__filename);
}).then(()=>{
assert.equal(als.get('id'), id);
returnsuperagent.get('http://www.baidu.com/');
}).then(()=>{
assert.equal(als.get('id'), id);
});
},100);
enable
enable the async hooks
constals=require('async-local-storage');
als.enable();
disable
disable the async hooks
constals=require('async-local-storage');
als.enable();
setTimeout(()=>{
als.disable();
},100);
size
get the size of storage
constals=require('async-local-storage');
als.enable();
setTimeout(()=>{
console.info(als.size());
},100);
scope
change the scope of call chain, it will be the call chain top (remove the parent of itself)
constals=require('async-local-storage');
constKoa=require('koa');
constassert=require('assert');
constapp=newKoa();
app.use(async(ctx,next)=>{
constid=ctx.get('X-Request-Id');
als.scope();
als.set('id', id);
awaitnext();
});
app.use(async(ctx,next)=>{
constid=ctx.get('X-Request-Id');
assert.equal(als.get('id'), id);
awaitnext();
});
app.use((ctx)=>{
ctx.body='OK';
});
set
set the value by key for the current id
key the key
value the value
linkedTop set the value linked to top
als.enable()
setTimeout(()=>{
als.scope();
constid=randomBytes();
setTimeout(()=>{
als.set('id', id,true);
},1);
setTimeout(()=>{
assert.equal(als.get('id'), id);
},10);
},10);
get
get the value by key, if will find from parent, self --> parent --> parent, until the value is not undefined
key the key
als.enable();
setTimeout(()=>{
als.scope();
constid=randomBytes();
setTimeout(()=>{
als.set('id', id,true);
},1);
setTimeout(()=>{
assert.equal(als.get('id'), id);
},10);
},10);
enableLinkedTop
enable linked top for default (default is disabled)