Javascript函数从另一个函数记录到控制台

Javascript Function logging to console from another function

本文关键字:函数 控制台 记录 另一个 Javascript      更新时间:2023-09-26

我有一个小问题,因为我缺乏JS的经验。。。

我的文件中有一个函数,它正确地记录到控制台,但不知何故,没有返回它记录的值(或者可能我不知道如何提取它。)

function getStoragex() {
    chrome.storage.sync.get('alertsOn', function(data) {
          var optionShowAlertsx = data;
          console.info("This is logging ok" + optionShowAlertsx.alertsOn);
          return optionShowAlertsx.alertsOn;
        });
    }

日志记录为:

DATA true 

稍后,我有这个(在另一个函数中)

var optionShowAlerts =  getStoragex();
console.info("This is logging undefined " + optionShowAlerts);

我做错了什么??

return语句位于传递给chrome.storage.sync.get的匿名函数内。getStoragex函数从不发出return,因此对它的调用会得到结果undefined

如果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);