【问题标题】:Wait for a response to a Dexie table lookup before proceeding在继续之前等待对 Dexie 表查找的响应
【发布时间】:2020-03-11 05:08:45
【问题描述】:

我正在使用一个名为 bugout 的库(这是一个基于 webtorrent 构建的 API)来创建 P2P 房间,但我需要它来根据使用 Dexie 查找表的值创建房间。

我知道这已经在 Stack Overflow 上重复了一百万次,但我仍然无法理解 Promise 或异步等待函数的概念。在此值可用之前,我需要不进行错误操作。但我也不想陷入回调地狱。

var room = db.profile.get(0, function (profile) {var ffname = profile.firstName;return ffname})
console.log(ffname) //returns undefined
var b = new Bugout(ffname);

我也试过了:

var room = db.profile.get(0, function (profile) {var ffname = profile.firstName;return ffname})
console.log(room) //returns undefined
var b = new Bugout(room);

我怎样才能用尽可能少的代码取回 ffname,而不是陷入一堆匿名或异步函数中,这些函数会将我锁定在 API 之外?

【问题讨论】:

  • 这就是回调的用途。您不能从异步调用中返回。将逻辑放在有返回值的代码中
  • 好的.. 所以我需要这个...? dexie.org/docs/Table/Table.get()
  • var room = db.profile.get(0, function (profile) {var ffname = profile.firstName; var b = new Bugout(ffname); })
  • 这就是我需要的!完美的!太感谢了! db.profile.get(0, function (profile) {var ffname = profile.firstName; var b = new Bugout(ffname); 如果您想用我更新的代码添加答案,我很乐意将其标记为答案。
  • 我知道我的问题并没有达到所有的指导方针,但你让我到达了我需要的地方,答案可能对其他人有帮助......我有编写代码,只是将它设置为房间变量是错误的方法。

标签: javascript dexie


【解决方案1】:

最简单最简单的方法是这样的:

async function getBugoutFromId(id) {
  var profile = await db.profile.get(id);
  var ffname = profile.firstName;
  console.log(ffname)
  var b = new Bugout(ffname);
  return b;
}

如果您希望在不使用 async/await 的情况下使用 Promise,请执行以下操作:

function getBugoutFromId(id) {
  return db.profile.get(id).then(profile => {        
    var ffname = profile.firstName;
    console.log(ffname)
    var b = new Bugout(ffname);
    return b;
  });
}

这两个函数的工作方式相同。它们中的任何一个都会依次返回一个承诺,所以当你调用它时。因此,无论您要对检索到的 Bugout 实例做什么,您都需要以与 Dexie 的 promise 相同的方式处理您自己的函数返回的 promise。

async function someOtherFunction() {
   var bugout = await getBugoutFromId(0);
   console.log ("Yeah! I have a bugout", bugout);
}

或者如果您不想使用 async/await:

function someOtherFunction() {
   return getBugoutFromId(0).then(bugout => {
     console.log ("Year! I have a bugout", bugout);
   });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-02
    • 1970-01-01
    • 2023-01-17
    • 2020-01-18
    • 2014-07-12
    • 2012-11-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多