我正在尝试在我的 Next.js 应用程序中有一个动态导入模块的单例实例。但是,我的当前实现似乎每次调用 getInstance
时都会初始化一个新实例。
以下是 gui.js
中的实现:
let dynamicallyImportPackage = async () => {
let GUI;
await import('three/examples/jsm/libs/dat.gui.module.js')
.then(module => {
GUI = module.GUI
})
.catch(e => console.log(e))
return GUI;
}
let GUI = (function () {
let instance;
return {
getInstance: async () => {
if (!instance) {
let GUIModule = await dynamicallyImportPackage();
instance = new GUIModule();
}
return instance;
}
};
})();
export default GUI;
并且我使用 GUI.getInstance().then(g => { ... })
对于这种共享状态,我通常会使用 React Context API 或 Redux,但在这种情况下,我需要它完全使用 ES6 JS 而不是 React。
答案 0 :(得分:1)
您需要缓存 promise,而不是实例,否则它会在第一个模块仍在加载且尚未分配 instance
变量时再次尝试导入模块(并实例化另一个实例)。
async function createInstance() {
const module = await import('three/examples/jsm/libs/dat.gui.module.js')
const { GUI } = module;
return new GUI();
}
let instancePromise = null;
export default function getInstance() {
if (!instancePromise) {
instancePromise = createInstance()
// .catch(e => {
// console.log(e); return ???;
// instancePromise = null; throw e;
// });
}
return instancePromise;
}