答应回叫和入站消息

时间:2019-04-27 03:18:52

标签: javascript es6-promise

我有一个页面,该页面将UI库作为脚本标签加载。我的页面具有lib.ready()函数,该函数库在加载后即会调用,因此我不执行原始调用,只是接收到调用。

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

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

听上去,promise是解决此问题的好方法,但是当我不调用我正在等待的任何东西时,我不确定如何设置它。我已经在考虑为回调创建承诺,但是我没有执行第一个呼叫。

如何构造代码以等待UI加载并返回消息?

//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.
}

1 个答案:

答案 0 :(得分:0)

我解决了这一问题,方法是在UI加载和加载后,保留接收到的数据消息的数组,以处理每个等待的消息。