-1

I've been googling for a long time now and can't find a solution. My current code:

let end = new Date().getTime();
if(Msg == "test") {
  // ...
}
db.set("start", new Date().getTime());

If I try to send db.get("start") it will send

[object Promise]

If I try to send db.get("start") - end it will send

NaN

I wanna measure the time between previous message and last one(that was just sent) so my solution for it is using the data base to keep the time when the last one was sent. This worked back when I coded a bot in python but now in JavaScript I can't get it to work.

Can anyone please help?

p.s Msg = msg.content. Not that important but whatever

MrMythical
  • 8,908
  • 2
  • 17
  • 45

1 Answers1

0

db.get() returns a promise, which you need to await

const start = await db.get("start")
console.log(start - end)
MrMythical
  • 8,908
  • 2
  • 17
  • 45
  • It gives me error: `SyntaxError: await is only valid in async functions and the top level bodies of modules` – Doctor Vaitzman Apr 29 '22 at 17:12
  • When I put it in an async function it returns "Promise { }" in the console. Idk what to do with it – Doctor Vaitzman Apr 29 '22 at 17:18
  • @DoctorVaitzman can you show the code you currently have? – MrMythical Apr 29 '22 at 17:39
  • I have been making so many changes to try and fix it... but anyway this is what it currently is: `async function duration(end) { const start = await db.get("start").then(value => {}); console.log(start); return (parseInt(start) - end); }` `let end = new Date().getTime(); //When he sends the next message end = end / 1000; console.log(duration(end)); ` `db.set("start", end.toString()).then(() => {});` – Doctor Vaitzman Apr 29 '22 at 17:53
  • @DoctorVaitzman `duration` is async, so it returns a promise which also needs to be awaited – MrMythical Apr 29 '22 at 18:03
  • where do I await it? – Doctor Vaitzman Apr 29 '22 at 18:15
  • @DoctorVaitzman what you can do is `duration(end).then(console.log)`, and it would log it. If you are trying to set the value to a variable, then `= await duration(end)` – MrMythical Apr 29 '22 at 18:27
  • Yeah but then we get to the cant await unless its in async function... – Doctor Vaitzman Apr 29 '22 at 18:41
  • Alright I got it working! Just had to change the fucntion it was in to async. lol dont know how I how I didnt realise it. Thanks a lot for the help! – Doctor Vaitzman Apr 29 '22 at 19:04
  • @DoctorVaitzman if this answered your question, consider accepting it by clicking the checkmark – MrMythical Apr 29 '22 at 20:48