首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >相关承诺

相关承诺
EN

Stack Overflow用户
提问于 2021-12-27 23:25:27
回答 2查看 30关注 0票数 0

在我的类型记录proyect中,我有一个配置和一个Controller类:

代码语言:javascript
复制
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);
        })
    }
}
代码语言:javascript
复制
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。

我的推理和代码有什么问题?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-12-27 23:28:33

代码语言:javascript
复制
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组合它们:

代码语言:javascript
复制
this.ready = Promise.all([
  this.readLogDir().then(res => { this.logDir = res; }),
  this.readLogFile().then(res => { this.logFile = res; })
]);
票数 0
EN

Stack Overflow用户

发布于 2021-12-27 23:38:13

我注意到OP文章的标题是关于有希望的链接。注意,node.js是异步的,在给定的实现中,这两个承诺是同时执行的。请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises#chaining

代码语言:javascript
复制
 this.readLogDir().then(res => {
   this.logDir = res; 
   this.readLogFile().then(res => { this.logFile = res; });
 });

链接^示例

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70501382

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档