Javascript函数从另一个函数记录到控制台
我有一个小问题,由于我对JS缺乏经验 我的文件中有一个函数,它正确地记录到控制台,但不知何故,没有返回它记录的相同值(或者可能我不知道如何提取它…) 日志记录为:Javascript函数从另一个函数记录到控制台,javascript,function,scope,Javascript,Function,Scope,我有一个小问题,由于我对JS缺乏经验 我的文件中有一个函数,它正确地记录到控制台,但不知何故,没有返回它记录的相同值(或者可能我不知道如何提取它…) 日志记录为: DATA true 稍后,我在另一个函数中 ) 我做错了什么???您的return语句在您传递给chrome.storage.sync.get的匿名函数中。您的getStoragex函数从不发出返回,因此对它的调用会得到结果未定义 如果chrome.storage.sync.get是一个同步函数(看起来它可能来自名称),则可以执行
DATA true
稍后,我在另一个函数中
)
我做错了什么???您的
return
语句在您传递给chrome.storage.sync.get的匿名函数中。您的getStoragex
函数从不发出返回
,因此对它的调用会得到结果未定义
如果chrome.storage.sync.get
是一个同步函数(看起来它可能来自名称),则可以执行以下操作:
function getStoragex() {
var rv;
chrome.storage.sync.get('alertsOn', function(data) {
var optionShowAlertsx = data;
console.info("This is logging ok" + optionShowAlertsx.alertsOn);
rv = optionShowAlertsx.alertsOn;
});
return rv;
}
(这种支撑方式我并不熟悉,如果我把它搞砸了,我道歉。)
编辑:在我看来,该名称中的sync
与同步或异步功能无关,而是与数据同步有关
如果是异步的,则不能从getStoragex
返回结果,因为getStoragex
在结果可用之前返回。在这种情况下,您可以接受一个回调,当您有结果时,您可以使用该结果进行回调:
function getStoragex(callback) {
chrome.storage.sync.get('alertsOn', function(data) {
var optionShowAlertsx = data;
console.info("This is logging ok" + optionShowAlertsx.alertsOn);
callback(optionShowAlertsx.alertsOn);
});
}
另一方面,承诺目前也越来越受欢迎。您可以考虑使用其中一种(有几种可用的实现)。如果chrome.storage.sync.get
是异步的,那么结果仍然是异步的。您的return
语句将值返回给它chrome.storage.sync.get
方法第二个参数本身。它将不会返回到getStoragex()方法
试试这个
function getStoragex() {
var optionShowAlertsx;
chrome.storage.sync.get('alertsOn', function(data) {
optionShowAlertsx = data;
console.info("This is logging ok" + optionShowAlertsx.alertsOn);
});
return optionShowAlertsx.alertsOn
}
var optionShowAlerts = getStoragex();
console.log("This is logging undefined " + optionShowAlerts);
刚开始读你的回复,我马上就发现了问题。我以前把它放在正确的位置,但我把它移到了线路的某个地方。。。谢谢!
function getStoragex(callback) {
chrome.storage.sync.get('alertsOn', function(data) {
var optionShowAlertsx = data;
console.info("This is logging ok" + optionShowAlertsx.alertsOn);
callback(optionShowAlertsx.alertsOn);
});
}
function getStoragex() {
var optionShowAlertsx;
chrome.storage.sync.get('alertsOn', function(data) {
optionShowAlertsx = data;
console.info("This is logging ok" + optionShowAlertsx.alertsOn);
});
return optionShowAlertsx.alertsOn
}
var optionShowAlerts = getStoragex();
console.log("This is logging undefined " + optionShowAlerts);