【问题标题】:can I obtain a value from a dexie DB without using the built-in promises我可以在不使用内置承诺的情况下从 dexie DB 获取值吗
【发布时间】:2025-12-01 19:05:02
【问题描述】:

我正在编写一个需要从中断处重新开始的离线网页。 我有页面来读取大型 JSON 数组,它构建各种表,它从表中读取,现在我需要“继续用户离开的地方”

在javascript中,我通常会得到一个值var todaysDataObtained=""; 但现在我需要从 dexie 数据库中获取“todaysDataObtained”,但一切似乎都基于承诺,并且 var 的实际设置立即返回“”,尽管控制台说现在应该将 var 设置为“未设置”

var todaysDataObtained="";

db.todaysShift.toArray().then((records) => { 
   todaysDataObtained= records[0]["theDate"];
   console.error ("todaysDate is "+records[0]["theDate"]);
  }).catch (function (error) {
   console.error ("Transaction aborted due to error: " + error);
   console.error ("todaysDate is NOT set");
   todaysDataObtained="not set";
  });

alert(todaysDataObtained);

那么如何将数据库条目返回到 javascript 变量中,强制 javascript 等到承诺完成并在承诺中正确设置 var。

一旦设置了 var,我就可以使用它来强制用户登录以获取 todaysData 或跳过该步骤并继续了解我已经拥有一个填充的数据库

谢谢凯文,

【问题讨论】:

    标签: dexie


    【解决方案1】:

    这就是 Promise 的工作方式。这实际上是一个异步操作,让您的浏览器可以同时呈现一些 HTML 或做其他类型的事情。 alert(todaysDataObtained); 发生在任何回调之前。 您应该真正从回调开始您的应用程序逻辑,此外不要使用 catch 处理程序:

    db.todaysShift.toArray().then(records => { 
      if (record.length === 0) {
        // startup with empty db
      } else {
        // startup with data if that is any different 
        // from the first case
      }
    })
    .catch (error => {
        // error handling
    });
    

    【讨论】:

      最近更新 更多