同步postMessage

Synchronous postMessage

有没有办法制作postMessage "a synchronous call"? 含义:

例如:

function doSomething() {
   targetiFrame.postMessage('actionA');
   handleMessage('actionA').then(function() {
      return true;
   });
}

function handleMessage(action) {
   return new Promise(function(resolve, reject) {
   });
}

当然,这不会起作用,因为我触发了 handleMessage,而它应该只有在收到正确的消息时才会触发。有没有办法等到收到 'actionA' 消息,然后才以 return true 结束函数?

我是这样解决问题的:

let doSomethingResolveCallback;
let doSomethingRejectCallback;

function doSomething() {
  return new Promise(resolve, reject) => {
    doSomethingResolveCallback = resolve;
    doSomethingRejectCallback = reject;
    targetiFrame.postMessage('actionA');
  }
}

// handles messages from the iFrame
function handleMessage(event) {
   if (event.action === "answerToActionA") {
     doSomethingResolveCallback(event.data);
   }
}