然后在Promise.resolve()之后没有触发的方法

时间:2017-06-29 09:09:09

标签: javascript ecmascript-6

在Ionic2中,我试图设计一个javascript方法,它将打开一个模态webview,让用户输入一些数据,然后在模态webview关闭时应该触发回调。

我正在尝试使用Promise实现这一目标。

这是计划:

var openWebviewPromise:any;

this.openWebview(path).then(()=>{
  //this line after then is never fired!
  console.log("do something when webview is closed");
});

openWebview = (path:string) => {
  // do something to listen to webview closed even
  this.openWebviewPromise = new Promise((resolve, reject) => {
    // open the modal webview here.
  });
  return this.openWebviewPromise;
}

// Then I listen to event when the modal iframe is closed manually by user, I tried to call .resolve when that happens, hoping then() will be called.
window.addEventListener('message', this.formCloseEventHandler);

formCloseEventHandler = (event:any) =>{
  if(event.data == "embed-auto-close-popup"){
    if(this.openWebviewPromise !== undefined){
      this.openWebviewPromise.resolve();
    }
  }
}

它不起作用。当modal关闭时,我们触发this.openWebviewPromise.resolve(),但不会触发then行。

1 个答案:

答案 0 :(得分:0)

你应该写

openWebview(path:string) {
  return new Promise((resolve, reject) => {
    … // open the modal webview here.
    … // do something to listen to webview closed even and call resolve()

    // Listen *here* to event when the modal iframe is closed manually by user
    window.addEventListener('message', (event:any) => {
      if (event.data == "embed-auto-close-popup") {
        resolve(); // or reject(new Error(…));
      }
    });
  });
}