Consider the following code run under NodeJS 14.4 on Windows:
const async_hooks = require('async_hooks');
const fs = require('fs');
const util = require('util');
let asyncLocalStorage = new async_hooks.AsyncLocalStorage();
asyncLocalStorage.enterWith({blah: 7});
function log(...args) {
fs.writeSync(1, `${util.format(...args)}\n`);
}
function getCurrentId() {
return async_hooks.executionAsyncId();
}
new Promise((res, rej) => {
log(`first promise: ${getCurrentId()}`);
res();
log(`first promise done`);
}).then(() => {
log(`second promise: ${getCurrentId()}`);
asyncLocalStorage.enterWith({id: 7});
log(`id in second promise=${asyncLocalStorage.getStore().id}`);
log(`second promise done`);
}).then(() => {
log(`third promise: ${getCurrentId()}`);
log(`id in third promise=${asyncLocalStorage.getStore().id}`);
});
I expected the local storage from the second promise to propagate to the third one. However, the output of this code is the following:
first promise: 1
first promise done
second promise: 3
id in second promise=7
second promise done
third promise: 4
id in third promise=undefined
If I turn on debugging via async-local-storage, the following output is revealed:
2(PROMISE) init by 1
first promise: 1
first promise done
3(PROMISE) init by 2 <-- when first promise is done, context for the second promise is init'd
4(PROMISE) init by 3 <-- but context for third promise is also initiated, before the second promise even ran!
second promise: 3
id in second promise=7 <-- so the async store is set only after the context for the third promise is init'd
second promise done
third promise: 4
id in third promise=undefined <-- which means AsyncLocalStorage did not copy the store to the third promise
Am I missing something in expecting the store to propagate to the third promise as well?