Here's my code:
const Database = require("@replit/database");
const db = new Database();
db.set("test", "wow").then(() => {});
console.log(db.list().then(keys => {}));
I have the database package installed, and it says that there is one key in the Database section of my repl, but it's not console logging the list of the keys, and I'm not getting an error. Only this is in the console:
Promise { <pending> }
Hint: hit control+c anytime to enter REPL.
There seems to be two problems:
set
and list
-- it's indeterminate which will fire first.then
s -- console.log()
is synchronously logging a pending promise rather than the result of the completed promise, which is only available in a then
callback.db.set("test", "wow")
.then(() => db.list()) // ensure `list` runs after `set` resolves
.then(keys => console.log(keys)) // ensure `keys` are logged after `list` resolves
You can also use async
/await
:
(async () => {
await db.set("test", "wow");
const keys = await db.list();
console.log(keys);
})();
This is generally considered to be more intuitive to read because it resembles synchronous code, but it's just syntactic sugar for the then
approach.