【问题标题】:Creating a Q promise and invoking it later创建一个 Q 承诺并稍后调用它
【发布时间】:2014-12-15 19:30:53
【问题描述】:

我正在尝试在打字稿中创建一个对话框系统。

预期用途是调用者会做这样的事情;

dialogBox.showDialog().then((result: DialogResult) => {
    // Handle the dialog result
});

我的DialogBox 类可能会有一些这样的方法;

private promise : Q.Promise<DialogResult>; 

public showDialog() : Q.Promise<DialogResult>{
    this.promise = ... // How to create this promise?

    return this.promise;
}

public void setResult(result : DialogResult){
    // What to do here?
}

每当用户单击对话框中的按钮时,都会调用类似的内容;

dialogBox.setResult(theResult);

这应该会解决/履行showDialog 方法创建的承诺。

但我无法真正弄清楚 Q 是否可以实现这一点,以及如何实现showDialogsetResult 的(与承诺相关的部分)。有人有什么想法吗?

更新完整性;感谢 Bergi,这是我最后的工作代码。最终使用了延迟

export class DialogBox implements INotification {
    private deferred: Q.Deferred<DialogResult>; 

    constructor(public message: string,
                public header: string,
                public buttons?: DialogResult[]) {
    }

    public showDialog(): Q.Promise<DialogResult> {
        this.deferred = Q.defer<DialogResult>();

        // My logic for displaying the box goes here

        return this.deferred.promise;
    }

    public setResult(result: DialogResult) {
        this.deferred.resolve(result);
    }
}

【问题讨论】:

标签: javascript typescript promise q


【解决方案1】:

您可以使用 deferred 存储为类的私有字段,或者使用 Promise constructor(这是首选)。

private deferred : Q.Deferred<DialogResult>; 

public showDialog() : Q.Promise<DialogResult>{
    this.deferred = Q.defer();
    // create dialog
    return this.deferred.promise;
}

public void setResult(result : DialogResult){
    this.deferred.resolve(result);
}

public showDialog() : Q.Promise<DialogResult>{
    return new Q.Promise(function(resolve) {
        // create dialog

        setResult = resolve;
        // call it somewhere
    })
}

【讨论】:

  • 谢谢!为什么首选 promise ctor?
  • 如果不引入那个额外的 Deferred 对象,它就不会那么冗长了。此外,如果回调函数(到Promise(),即创建对话框并设置异步侦听器的函数)抛出,它会自动拒绝承诺。
  • 公平地说,如果您将其分配给setResult,如此处所示,您并不能真正得到很好的保证,而延期也一样好。另一方面,将解析逻辑放在构造函数中会起作用。
  • resolve 赋值给setResult 只是为了表明应该只调用resolve 而不是私有的setResult 方法。
猜你喜欢
  • 2017-08-12
  • 1970-01-01
  • 1970-01-01
  • 2015-04-15
  • 2016-04-05
  • 1970-01-01
  • 1970-01-01
  • 2014-12-19
  • 2020-12-05
相关资源
最近更新 更多