Javascript Chrome扩展:can';t一次单击就无法从存储中获取价值
我有一个使用存储的chrome扩展,我无法通过点击回车键从存储中获取值 只有一个输入字段。用户输入一个值并按enter键后,扩展应从存储器中获取该值,并将用户的输入添加到此值中。第一次按enter键不起作用,但如果用户再次单击enter键,则会看到存储的值 我假设问题在于函数的顺序,但我不知道具体在哪里 按正确顺序编码:Javascript Chrome扩展:can';t一次单击就无法从存储中获取价值,javascript,google-chrome,google-chrome-extension,google-chrome-storage,Javascript,Google Chrome,Google Chrome Extension,Google Chrome Storage,我有一个使用存储的chrome扩展,我无法通过点击回车键从存储中获取值 只有一个输入字段。用户输入一个值并按enter键后,扩展应从存储器中获取该值,并将用户的输入添加到此值中。第一次按enter键不起作用,但如果用户再次单击enter键,则会看到存储的值 我假设问题在于函数的顺序,但我不知道具体在哪里 按正确顺序编码: var repo, moduleCodes, url; // Third process function getStoredUrl() { chrome.stora
var repo, moduleCodes, url;
// Third process
function getStoredUrl() {
chrome.storage.sync.get(function (item) {
url = item.savedUrl;
});
}
// Fourth process
function setVariables() {
repo = document.getElementById("repo").value.toLowerCase();
moduleCodes = {
admin: "EHEALTHADM"
};
}
// Second process
function openGraph() {
getStoredUrl();
setVariables();
if (moduleCodes[repo] !== undefined) {
// ERROR: field "test" doesn't have value url, but should to have
document.getElementById("test").value = url;
//window.open(url + moduleCodes[repo]);
} else {
returnError("Can't find repo " + repo, "repo");
}
}
var enter = 13;
// First process
function inputRepoListener(e) {
"use strict";
if (e.keyCode === enter) {
openGraph();
}
}
整个代码都可以在gitHub repo上看到:这是一个典型的竞争条件,由异步方法调用引起 对
storage.sync.get
的调用是异步的,即在检索存储值时,正常的程序流将继续。这意味着(仍然是空的)url
变量分配给id为test
的元素也发生在存储值检索完成之前
解决方案:将检索到存储值后应该发生的所有事情移动到storage.sync.get的回调中。例如,如果您这样分配url
,它将工作
chrome.storage.sync.get(function (item) {
url = item.savedUrl;
document.getElementById("test").value = url;
});
因此,您需要重新构造代码以满足此条件。getStoredUrl
在运行对sync.get
的回调之前终止。(事实上,您的所有代码都是在回调有机会运行之前运行的。)看,我不会确切地将其称为“竞争条件”,因为这两个函数实际上并不并行执行。在任何情况下,这都应该作为规范问题的副本来结束。