Implementing timeouts for node.js callbacks

前端 未结 4 561
执念已碎
执念已碎 2020-12-25 11:07

This is a typical situation in node.js:

asyncFunction(arguments, callback);

When asynFunction completes, callback

4条回答
  •  梦毁少年i
    2020-12-25 12:04

    I ran into the same problem with a content script trying to open the port on the BG extension before the BG extension was ready. A work around was to wait for the BG extension to reply to a message and repeat this till successful. Here are the code snippets.

    Content Script:

    var nTimes     = 10;
    var bIsReady = false;
    checkBGReady();
    function checkBGReady() {
      if (!bIsReady) {
        chrome.runtime.sendMessage({msgText: "hello "+nTimes}, function(response) {
          if (response && response.ack) {
            console.log("have response:"+response.ack+" "+nTimes);
            bIsReady = true;
            // continue with initialization
            bootStrap(sURL);
            checkReady();
          } else {
            console.log("have no ack response %o",response);
          }
        });
      }
      nTimes -= 1;
      if (nTimes > 0 && !bIsReady) {
        setTimeout(checkBGReady,100);
      }
    }
    

    BG Extension

      chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
        console.log(sender.tab ?"from a content script:" + sender.tab.url :"from the extension");
        if (request.msgText) {
          console.log("Have msg "+request.msgText);
           sendResponse({ack: "have contact "+request.msgText});
        }
      });
    

    In my case it usually took after the first 100ms delay.

提交回复
热议问题