1

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.
  • Try moving the `console.log` into the `db.set(...).then( /* move it here */ )` callback to avoid a race condition. Secondly, you're not doing anything with `keys => {}`. You probably want `console.log(keys)` here. (I haven't used repl.it's database but this code doesn't make sense from a promises standpoint). Empty `.then`s are pointless. If this works, feel free to let me know and I can convert to an answer: `db.set("test", "wow").then(() => db.list()).then(keys => console.log(keys))` – ggorlen Apr 09 '21 at 18:49
  • Haha it worked, thanks! If you make it an answer I can upvote and mark it best answer C: – Banatato Melonwi Apr 09 '21 at 18:54

1 Answers1

1

There seems to be two problems:

  1. The two promise chains are disconnected, so it's a race condition between set and list -- it's indeterminate which will fire first.
  2. Use the thens -- 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.

ggorlen
  • 44,755
  • 7
  • 76
  • 106