How to wait for an asynchronous method's callback return value?

后端 未结 1 1539
我在风中等你
我在风中等你 2020-12-18 00:50

I know that waiting for an asynchronous method is stupid, one should use callbacks instead. But what if an third party API forces you to be synchronous?

I\'m develop

相关标签:
1条回答
  • 2020-12-18 01:32

    Maybe you can solve the problem by keeping track of the tab URLs?:

    1. When the app starts, get all open tab URLs by using chrome.tabs.query
    2. Subscribe to chrome.tabs.onUpdated and chrome.tabs.onRemoved and add/remove/update the URLs when they change.

    Some kind of code example based on the documentation:

    var tabUrlHandler = (function() {
       // All opened urls
       var urls = {},
    
       queryTabsCallback = function(allTabs) {
          allTabs && allTabs.forEach(function(tab) {
              urls[tab.id] = tab.url;
          });
       },
    
       updateTabCallback = function(tabId, changeinfo, tab) {
           urls[tabId] = tab.url;
       },
    
       removeTabCallback = function(tabId, removeinfo) {
           delete urls[tabId]; 
       };
    
       // init
       chrome.tabs.query({ active: true }, queryTabsCallback);
       chrome.tabs.onUpdated.addListener(updateTabCallback);
       chrome.tabs.onRemoved.addListener(removeTabCallback);
    
       return {
         contains: function(url) {
            for (var urlId in urls) {
               if (urls[urlId] == url) {
                  return true;
               }
            }
    
            return false;
         }
       };
    
    }());
    

    Now you should be able to ask the tabUrlHandler directly in your onBeforeRequestMethod:

    function onBeforeRequest(details) {
      var websiteAlreadyOpenInOtherTab = tabUrlHandler.contains(details.url);
    
      if (websiteAlreadyOpenInOtherTab) {
        return { cancel: true };
      }
    }
    
    0 讨论(0)
提交回复
热议问题