Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/417.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在JavaScript中使用异步函数_Javascript_Asynchronous_Google Chrome Extension - Fatal编程技术网

在JavaScript中使用异步函数

在JavaScript中使用异步函数,javascript,asynchronous,google-chrome-extension,Javascript,Asynchronous,Google Chrome Extension,因此,下一个函数应该在chrome存储中的预存储数组中搜索与当前日期相等的某个索引: function comparingDates(fn) { var currentDate = new Date(); var j; chrome.storage.sync.get("storeDates", function comparing(items) { if (!chrome.runtime.error) { var arrayDates = items.st

因此,下一个函数应该在chrome存储中的预存储数组中搜索与当前日期相等的某个索引:

function comparingDates(fn) {
var currentDate = new Date();
var j;
chrome.storage.sync.get("storeDates", function comparing(items) {
        if (!chrome.runtime.error) {
            var arrayDates = items.storeDates;
            j = arrayDates.findIndex(x => x.date == currentDate.getDate());
            console.log(j);
           fn(j);
        };
   });
};
fn
是将找到的相应索引发送到此回调的函数:

comparingDates(function (l1) {
        if (!l1) {
            console.log("error");
        } else {
           currentDay = l1;
            console.log("succes");
        };
变量
currentDay
在之前声明

运行函数并发送值后,采用未定义
l1
时的条件


如果发生错误,不完全了解如何处理异步函数是很难掌握的。对它进行一些搜索并不能为实际参考提供很好的示例。

findIndex返回-1表示未找到,如果要这样做的话

if (-1) console.log("Is Truthy")
你会得到控制台线路。如果项目位于第一个索引(aka 0)中,那么检查也将失败

你应该检查-1,而不是truthy

  comparingDates(function (l1) {
    if (l1===-1) {
      console.log("error");
    } else {
      currentDay = l1;
      console.log("success");
    }
  });

如果你这么说的话

  var l1;
  comparingDates(function (l1) {
    if (l1===-1) {
      console.log("error");
    } else {
      currentDay = l1;
      console.log("success");
    }
  });
  console.log(l1) <-- is undefined
var-l1;
比较日期(函数(l1){
如果(l1==-1){
控制台日志(“错误”);
}否则{
currentDay=l1;
控制台日志(“成功”);
}
});

console.log(l1)您缺少一个结束符)并且findIndex返回-1表示找不到,所以如果项在第一个索引中,那么它将是一个“错误”,并且找不到是有效的???@epascarello运行代码时,console.log(j)传递正确的索引。所以我认为那部分不是问题。不管怎样,你能告诉我你将如何解决这个问题。我不确定短语“当
l1
未定义时采用条件”是什么意思。你的意思是当你调试它时,
li
参数是
undefined
?@MikeMcCaughan是的,就是这样。对不起,我不知道如何表达我自己。所以你的问题不是你上面所说的,而是没有显示的代码……LOL@pizza类比。这真的很好,除了在这种情况下,因为您没有异步等待HTTP请求或数据库查询或类似的东西,这不像订购比萨饼,因为比萨饼送货员控制比萨饼到达的时间,但在这里您控制调用函数解析值的时间,对吗?这更像是把你自己的比萨饼放在烤箱里,当你忘了把它从烤箱里拿出来时,想知道为什么它还没有放在桌子上。
chrome.storage.sync.get(“storeDates”
是送货员,穿着破旧的福特护卫车,没有排气管,但有漂亮的带旋转器的轮辋。