1

I am using NEDB for some local storage in an NodeJS Application. Therefore I do have an handlerscript "nedbhandler.js" which I do require in my main.js.

var NEDB = require('./nedbhandler.js');

async function test(){
    var value = await NEDB.getValue_byID(1);
    console.log(value)
}

test()

while in the nedbhandler.js is my query handled like this:

async function getValue_byID(id){
    db.config.findOne({ _id: id }, function (err, doc) {
        callback(doc);
    });
    function callback(doc) {
        console.log(doc)
        return doc;
    }
}

exports.getValue_byID = getValue_byID;

While the console from nedbhandler.js logs the expected value, the main.js still is undefined.

What would be the best practice to load all config querys before loading next function in the main.js?

Matthias
  • 485
  • 7
  • 21
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – eol Nov 16 '20 at 10:30
  • Hi, no unfortuanetly not. I copied and pasted the Chapter: ES2017+: Promises with async/await in my main.js but it still returns undefined. – Matthias Nov 16 '20 at 11:06
  • Show us your updated code, please. – eol Nov 16 '20 at 12:32
  • Your callback inside `getalueById` is happening in non-blocking mode(asynchronous). So when you are calling `getValueById` function with `await`. It will simply return undefined from function as it will not wait for `db.config.findOne` again non-blocking. Either you wait for `findone` to complete or try explicitly returning promise and resolve it when value is found. – R.Sarkar Nov 16 '20 at 13:01

1 Answers1

1

You want your getValue_byID function to return a promise

function getValue_byID(id){
    return new Promise((resolve, reject) => {
        db.config.findOne({ _id: id }, (err, doc) => {
            err ? reject(err) : resolve(doc);
        });
    });
}

Note how I changed the function keyword to the more modern => syntax. It is also considered better practice to use const and let insteadof var

There is a wrapper module for nedb, called NeDB-promises. It does more or less what I have done here, so you can use async/await instead of callbacks.