Reputation: 3331
I'm using a library called bugout (which is an API built on webtorrent) to create a P2P room but I need it to create the room based on a value from a table lookup using Dexie.
I know this has been rehashed a million times on Stack Overflow, but I'm still having trouble grasping the concept of promises or async await functions. I need the bugout operations to not proceed until this value is available. But I also don't want to get stuck in callback 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);
I've also tried:
var room = db.profile.get(0, function (profile) {var ffname = profile.firstName;return ffname})
console.log(room) //returns undefined
var b = new Bugout(room);
How can I get ffname back with as little code as possible and not get stuck in a bunch of anonymous or asynchronous functions that will lock me out of the APIs?
Upvotes: 2
Views: 1168
Reputation: 5671
The easiest and simplest way is this:
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;
}
If you would prefer consuming promises without using async/await, do the following:
function getBugoutFromId(id) {
return db.profile.get(id).then(profile => {
var ffname = profile.firstName;
console.log(ffname)
var b = new Bugout(ffname);
return b;
});
}
The two functions works identically. Any of them returns a promise in its turn, so when you have called it. So whatever you are going to do with the retrieved Bugout instance, you need to handle the promise that your own function returns in the same manner as you did with the promise from Dexie.
async function someOtherFunction() {
var bugout = await getBugoutFromId(0);
console.log ("Yeah! I have a bugout", bugout);
}
or if you prefer not using async/await:
function someOtherFunction() {
return getBugoutFromId(0).then(bugout => {
console.log ("Year! I have a bugout", bugout);
});
}
Upvotes: 2