同步执行异步功能 [英] Executing asynchronous function , synchronously
问题描述
我正在制作Chrome扩展程序,通过弹出窗口阻止添加到本地存储的特定网站。我认为这个代码中的问题是,它在chrome.storage.local.get的回调完成之前返回。
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);
推荐答案
em>异步函数 webRequest
阻止侦听器。这是没有办法的,哈克或其他。由于JavaScript是单线程的,因此基本上是不可能的;在当前函数执行完成之前,异步操作甚至不会启动。
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.
将 blocked_sites
保存到一个变量中,并在 chrome.storage.onChanged
事件。这样,您将拥有设置的同步缓存。
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.
这篇关于同步执行异步功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!