如何将承诺作为参数传递

How to pass a promise as a parameter

我想将一个 promise 作为参数传递给另一个函数,将其用作回调。 我的代码如下

Component 1
function1() {
    let promise: Promise<any>;
    this.function2(promise);
    promise.then(response => console.log(response));
}

Component 2
function2(promise) {
    // Some Code 
    this.dialog.afterClosed().subscribe(data => {
       promise.resolve(data);
    });
}

这样做会在函数1中产生错误,错误是:Cannot read 属性 'then' of undefined

也许您想做的是:

function1() {
  const promise: Promise = new Promise((resolve, reject) => {
    this.function2(resolve);
  });

  promise.then(response => console.log(response));
}

function2(resolveFn: any) {
    // Some Code 
    this.dialog.afterClosed().subscribe(data => {
       resolveFn(data);
    });
}

[更新]: IMO,你应该完全用可观察对象来做(这里不需要承诺):

function1() {
  const afterClosed$: Observable<any> = this.function2();
  afterClosed$.subscribe((response: any) => console.log(response));
}

function2(): Observable<any> {
  // Some Code 
  return this.dialog.afterClosed();
}