AsyncLocalStorage
This class creates stores that stay coherent through asynchronous operations.
非同期操作を通して一貫したストアを作成する。
名前が誤解を招きやすい。ブラウザのlocalStorageとは関係がない
contextという方がニュアンスが近いと思う
AsyncなLocalStorage ❌
AsyncLocalなStorage ⭕
runでstoreに値をsetして実行
ここから呼ばれた操作内でgetStoreしたものは、最初にsetした値が触れる
要するに、明示的に引数として渡さなくても、何らかの状態を保持して使えるようにする
dynamicなscopeとして使える
DIとしても使える
code:js
import http from 'node:http';
import { AsyncLocalStorage } from 'node:async_hooks';
const asyncLocalStorage = new AsyncLocalStorage();
function logWithId(msg) {
const id = asyncLocalStorage.getStore();
console.log(${id !== undefined ? id : '-'}:, msg);
}
let idSeq = 0;
http.createServer((req, res) => {
asyncLocalStorage.run(idSeq++, () => {
logWithId('start');
// Imagine any chain of async operations here
setImmediate(() => {
logWithId('finish');
res.end();
});
});
}).listen(8080);
// Prints:
// 0: start
// 1: start
// 0: finish
// 1: finish
値の中身を確定させる前に、値に対する操作を記述できる
ブラウザにも欲しいですねmiyamonz.icon