创建一个Q承诺并稍后调用它
Creating a Q promise and invoking it later
我正在尝试用typescript创建一个对话框系统。
预期的用途是,呼叫者会做这样的事情;
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是否可以实现这一点,所以,如何实现showDialog
和setResult
的(与承诺相关的部分)。有人有什么想法吗?
完整性更新;感谢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);
}
}
您可以使用作为类的私有字段存储的deferred,也可以使用Promise
构造函数(首选)。
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
})
}
相关文章:
- 等待循环调用的所有承诺完成
- AngularJS因果报应测试规范承诺未解析,且未调用.then()
- 谷歌日历 api 调用可以在角度工厂内返回承诺吗?
- JavaScript - 返回承诺和/或调用回调
- 如何在使用替代承诺时解释 ajax 调用中的错误
- 递归承诺调用 - 内存范围变量问题
- “未捕获(在承诺中)”在获取“then”方法中调用拒绝函数时
- 使用 Promise 在另一个函数中调用带有 Bluebird 承诺库的函数
- javascript承诺在循环中或如何逐个调用函数
- 按照承诺,通过与chai的函数调用验证已解析承诺的内容
- 基于DOM插入承诺对API调用进行限制
- 在 Mocha 中,返回将被拒绝的承诺与调用 done(err) 的效果不同
- 进行多个 http 调用并使用承诺合并结果
- 如何在第一次调用后重新调用承诺
- Javascript 承诺 .catch 仍然调用 final variable.then
- 如何递归调用承诺函数
- 测试使用摩卡在其中调用承诺的函数
- 如何在承诺链中调用承诺通知
- jQuery递归AJAX调用承诺
- AngularJS多次处理调用承诺