Executing asynchronous function , synchronously

谁说我不能喝 提交于 2019-12-13 04:48:18

问题


I am making a chrome extension that blocks specific sites added to local storage through popup window. I think the problem in this code is, it returns before completion of chrome.storage.local.get's callback. How can I make it wait for sometime before returning ?

chrome.webRequest.onBeforeRequest.addListener(
function(details) {

var matched = false;

chrome.storage.local.get ( 'blocked_sites', function ( sites ) {
   var bsites = sites.blocked_sites;
   for ( i = 0, size = bsites.length; i < size; i++ ) {
    if ( details.url.indexOf( "://" + bsites[i] + "/" ) != -1 ) {
      matched = true;
    } // end if 
  } // end for

});
// WAIT HERE FOR VALUE OF MATCHED TO BE SET BY CALLBACK
return { cancel: matched };
},
{ urls: ["<all_urls>"] },
["blocking"] );

chrome.storage.local.set({'blocked_sites': [ 'www.topnotchdev.com'] }, null);

回答1:


You can't call any asynchronous function in webRequest blocking listeners. There is no way around it, hacky or otherwise. It is fundamentally impossible, since JavaScript is single-threaded; an async operation won't even start before the current function finishes executing.

This means you cannot rely on asynchronous storage; you must have a local synchronous cache for it.

Save blocked_sites to a variable, and update it on chrome.storage.onChanged event. This way, you'll have a synchronous cache of the setting.




回答2:


With the way your code structured you won't be able to make return { cancel: matched }; execute after the callback. The reason is because return { cancel: matched }; is run in one execution frame ( the same that calls chrome.storage.local.get ) and the callback is run in some future execution frame. When you call asynchronous method it can only insert the callback into event loop for some future time, by the time that callback is executed return { cancel: matched }; is already executed.



来源:https://stackoverflow.com/questions/33681539/executing-asynchronous-function-synchronously

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!