在我的类型记录proyect中,我有一个配置和一个Controller类:
class Config {
public Ready: Promise<any>;
private logDir: string = 'dir1';
private logFile: string = 'file1';
private client = new Etcd3();
constructor(defaultLogDir?: string, defaultLogFile?: string){
this.Ready = new Promise((resolve, reject) => {
this.readLogDir().then(res => { this.logDir = res; });
this.readLogFile().then(res => { this.logFile = res; });
resolve(undefined);
})
}
}class Controller {
public Ready: Promise<any>;
public config: Config = new Config();
private logDir: string = 'dir2';
private logFile: string = 'file2';
constructor(){
this.Ready = new Promise((resolve, reject) => {
this.config.Ready.then(() => {
this.logDir = this.config.getLogDir();
this.logFile = this.config.getLogFile();
resolve(undefined);
})
})
}
}由于配置类必须与I/O和服务器连接一起工作,因此可以(准备好)确定类何时可用,因此类总是按如下方式调用:config.then(() => {code})。这种工作方式是经过测试和行为正确隔离的。
现在,Controller类以同样的方式工作,因此,当它被正确地调用:controller.then(() => {code})时,它应该意味着Config对象也准备好了,但是情况并非如此,因为控制器分布的值是dir2和file2。
我的推理和代码有什么问题?
发布于 2021-12-27 23:28:33
new Promise((resolve, reject) => {
this.readLogDir().then(res => { this.logDir = res; });
this.readLogFile().then(res => { this.logFile = res; });
resolve(undefined);
})这就创建了一个新的承诺,它启动了一些异步的东西,然后立即决定为未定义的。在调用resolve之前,您不需要等待任何东西。
因为您已经有了承诺,所以根本不需要使用new Promise构造函数。只有当您将不使用承诺的内容转换为实际应用时,才真正需要该构造函数。您可以为读取logDir和logFile创建两个承诺,然后使用Promise.all组合它们:
this.ready = Promise.all([
this.readLogDir().then(res => { this.logDir = res; }),
this.readLogFile().then(res => { this.logFile = res; })
]);发布于 2021-12-27 23:38:13
我注意到OP文章的标题是关于有希望的链接。注意,node.js是异步的,在给定的实现中,这两个承诺是同时执行的。请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises#chaining
this.readLogDir().then(res => {
this.logDir = res;
this.readLogFile().then(res => { this.logFile = res; });
});链接^示例
https://stackoverflow.com/questions/70501382
复制相似问题