具有单例设计模式的 NodeJS 异步类
问题: 通过类中的异步调用实现单例设计模式。当我将模块导入到第二个文件中时,我无法获取值。
案例: 最终我想在不记名令牌过期时实现此逻辑以进行更新。我有多个依赖于令牌的函数。因此,当我收到 403 错误时,我将更新令牌,并且所有其他功能也可以访问此更新的令牌。
脚本 1:
//File1.js
import axios from "axios";
async function getJson(n) {
const req = await axios.get(
`https://jsonplaceholder.typicode.com/todos/${n}`
);
return req.data.title;
}
class Todo {
constructor() {
if (Todo.instance == null) {
this.title;
Todo.instance = this;
}
return Todo.instance;
}
async init() {
this.title = await getJson(1);
}
async updateTodo(n) {
this.title = await getJson(n);
}
getTodo() {
return this.title;
}
}
const todo = await new Todo().init();
export default todo;
脚本 2:
const todo = await import('./File1.js');
console.log(todo); //[Module: null prototype] { default: [AsyncFunction (anonymous)] }
todo.updateTodo(3) //TypeError: todo.updateTodo is not a function
脚本 2.1:
import todo from './File1.js';
await todo.init();
console.log(todo.getTodo())
await todo.updateTodo(2)
console.log(todo.getTodo())
Problem:
Implement the singleton design pattern with async calls in the class. I can't get the values when i import the module into a second file.
Case:
Eventually i want to implement this logic for a bearer token update when it expires. I have multiple functions that relies on the token. So when i get a 403 i will update the token and all the other function have acces to this updated token as well.
Script 1:
//File1.js
import axios from "axios";
async function getJson(n) {
const req = await axios.get(
`https://jsonplaceholder.typicode.com/todos/${n}`
);
return req.data.title;
}
class Todo {
constructor() {
if (Todo.instance == null) {
this.title;
Todo.instance = this;
}
return Todo.instance;
}
async init() {
this.title = await getJson(1);
}
async updateTodo(n) {
this.title = await getJson(n);
}
getTodo() {
return this.title;
}
}
const todo = await new Todo().init();
export default todo;
Script 2:
const todo = await import('./File1.js');
console.log(todo); //[Module: null prototype] { default: [AsyncFunction (anonymous)] }
todo.updateTodo(3) //TypeError: todo.updateTodo is not a function
Script 2.1:
import todo from './File1.js';
await todo.init();
console.log(todo.getTodo())
await todo.updateTodo(2)
console.log(todo.getTodo())
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
动态导入与常规导入不同。当您这样做时:
module
将等于默认导出,例如:在动态导入 (
import()
) 中,但是,您必须手动访问默认导出:所以在你的代码中你会这样做:
Dynamic imports are different from regular imports. When you do:
module
will be equal to the default export, something like:In dynamic imports (
import()
), however, you have to manually access the default export:So in your code you would be doing: