UNPKG

@modern-js/runtime-utils

Version:

A Progressive React Framework for modern web development.

46 lines (45 loc) 1.18 kB
import * as ah from "async_hooks"; const createStorage = () => { let storage2; if (typeof ah.AsyncLocalStorage !== "undefined") { storage2 = new ah.AsyncLocalStorage(); } const run = (context, cb) => { if (!storage2) { throw new Error(`Unable to use async_hook, please confirm the node version >= 12.17 `); } return new Promise((resolve, reject) => { storage2.run(context, () => { try { return resolve(cb()); } catch (error) { return reject(error); } }); }); }; const useContext = () => { if (!storage2) { throw new Error(`Unable to use async_hook, please confirm the node version >= 12.17 `); } const context = storage2 === null || storage2 === void 0 ? void 0 : storage2.getStore(); if (!context) { throw new Error(`Can't call useContext out of scope, make sure @modern-js/runtime-utils is a single version in node_modules`); } return context; }; return { run, useContext }; }; const storage = createStorage(); const getAsyncLocalStorage = () => { return storage; }; export { getAsyncLocalStorage, storage };