nedb icon indicating copy to clipboard operation
nedb copied to clipboard

how to load database in sync?

Open TangMonk opened this issue 8 years ago • 6 comments

TangMonk avatar Jan 03 '17 03:01 TangMonk

@TangMonk I think it is impossible as Node fs IO is async by default. Possible solutions :

  • Use Promises and continue in callbacks/then
  • Use ES7 Async/Await so you can code like normal sync
  • Implement custom storage provider (not supported yet here) and then using node sync fs methods.

pi0 avatar Jan 03 '17 07:01 pi0

@pi0, thanks I am using Asnyc/Await to fix that

TangMonk avatar Jan 03 '17 07:01 TangMonk

ES7 Asnyc/Await not work:

app.get('/devices', async (req, res) => {
  let result = await db.find({})
  res.send(result)
})

with error:

(node:53615) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Converting circular structure to JSON
(node:53615) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

TangMonk avatar Jan 03 '17 07:01 TangMonk

Try this:

app.get('/devices', async (req, res) => {
  let result = await db.find({})
  res.send(JSON.stringify(result))
})

pi0 avatar Jan 03 '17 07:01 pi0

@pi0 thanks , but not work.

  1. I think there is not necessary JSON.stringify(result), because using normal callback without JSON.stringify(result) works too.

  2. I think the problem is that nedb not support Promise, So Async/Await can not work normally #344

Now I am using nedb-promise instead

TangMonk avatar Jan 03 '17 08:01 TangMonk

Is there any chance to have native promise support panned? It would be a great addition.

@TangMonk I am currently using FeathersJS with nedb out of the box and not yet very familiar with. Do I have to do some extra work to adapt the project with nedb-promise? Can both works separately? :thinking:

soullivaneuh avatar Oct 05 '20 20:10 soullivaneuh