[英]Executing asynchronous function , synchronously
I am making a chrome extension that blocks specific sites added to local storage through popup window. 我正在制作一个chrome扩展程序,该程序阻止通过弹出窗口添加到本地存储的特定站点。 I think the problem in this code is, it returns before completion of chrome.storage.local.get's callback. 我认为这段代码中的问题是,它会在chrome.storage.local.get的回调完成之前返回。 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);
You can't call any asynchronous function in webRequest
blocking listeners. 您无法在webRequest
阻止侦听器中调用任何异步函数。 There is no way around it, hacky or otherwise. 没有办法解决,无论是hacky还是其他方式。 It is fundamentally impossible, since JavaScript is single-threaded; 从根本上讲是不可能的,因为JavaScript是单线程的。 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. 将blocked_sites
保存为变量,并在chrome.storage.onChanged
事件上chrome.storage.onChanged
更新。 This way, you'll have a synchronous cache of the setting. 这样,您将拥有该设置的同步缓存。
With the way your code structured you won't be able to make return { cancel: matched };
使用代码的结构化方式,您将无法获得return { cancel: matched };
execute after the callback. 在回调之后执行。 The reason is because return { cancel: matched };
原因是因为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. 在一个执行框架中运行(与调用chrome.storage.local.get
相同),而回调在将来的某个执行框架中运行。 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 };
当您调用异步方法时,它只能在将来的某个时间将回调插入事件循环中,直到执行回调时为止return { cancel: matched };
is already executed. 已经执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.