我正在使用一个名为 bugout 的库(这是一个基于 webtorrent 构建的 API)来创建 P2P 房间,但我需要它根据使用 Dexie 进行表查找的值来创建房间。
我知道这已经在 Stack Overflow 上被重复了一百万次,但我仍然无法理解 Promise 或 async wait 函数的概念。我需要在该值可用之前停止错误操作。但我也不想陷入回调 hell 。
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 之外的匿名或异步函数?
最佳答案
最简单的方法是这样的:
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;
});
}
这两个函数的工作原理相同。他们中的任何一个都会依次返回一个 promise ,所以当你调用它时。因此,无论您要如何处理检索到的 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);
});
}
关于javascript - 等待 Dexie 表查找的响应,然后再继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58870376/