承诺回调和入站消息

Promise for a callback and inbound message

我有一个页面加载了一个 UI 库作为脚本标签。我的页面有一个库在加载后调用的 lib.ready() 函数,所以我没有执行原始调用,只是接收调用。

我的页面也在等待来自外部实体的消息(又名事件),其中包含我需要在 UI 中显示的数据。有时消息在 UI 加载之前出现并且我的填充例程失败。

当然,一旦 UI 准备就绪,我就无法调用填充例程,因为消息数据可能尚未到达。

promise 听起来是解决此问题的好方法,但我不确定当我不调用任何我正在等待的东西时如何设置它。我看过创建回调承诺,但我没有执行第一个调用。

如何构造我的代码以等待 UI 加载并将消息发送到 return?

//This is the function the UI library calls when it's loaded itself.
uilib.ready(function () {
    uilib.ui({
            view: "layout",
            rows: [tabView]    //My components to show in the UI
        });   
}

//This is a Chrome extension, waiting for a message from a web page.
//Once I get the message I populate the UI with the data.
backgroundPageConnection.onMessage.addListener(function (message) {
    switch (message.action) {
        case WSI_SEND_RULES:
            displayRules(message.data);
            break;
    }
});

//This is how I display the data.
function displayRules(rulesTreeData) {
    clearRules();
    $$("rulesWidget").parse(rulesTreeData);  //if ui isn't loaded this fails.
}

我通过保存在 UI 加载之前接收到的数据消息的数组来解决它,一旦加载,就处理每个等待的消息。