2014-10-20 48 views
1

我试图在打字稿中创建一个对话框系统。创建一个Q promise并稍后调用它

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

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); 
    } 
} 
+1

退房的源ngDialog。它具有基于承诺的对话框的实现。 https://github.com/likeastore/ngDialog – mccainz 2014-10-20 18:50:22

回答

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 
    }) 
} 
+0

谢谢!为什么承诺ctor首选? – havardhu 2014-10-20 19:08:06

+2

没有引入额外的Deferred对象,它就不那么冗长了。此外,如果回调函数(对'Promise()',即创建对话框并设置异步侦听器的函数)抛出,它会自动拒绝承诺。 – Bergi 2014-10-20 20:04:03

+0

公平地说,如果你将它赋值给'setResult',如下所示,你确实没有得到很好的保证,延期也是如此。另一方面,在构造函数中放置解析逻辑将起作用。 – 2014-10-21 16:15:24

相关问题