Aung Htet Paing
Aung Htet Paing

Reputation: 131

Can't return data from callback function at NodeJS

When i create new variable and assign callback function, But data cannot return from callback function. Undefined is occurring at new variable.

const nedb = require('nedb');
const user = new nedb({ filename: './builds/database/users.db', autoload: true });
var s = user.find({}, function (err,docs) {
  if(docs.length == 0) {
    var data = false;
  } else {
    var data = docs;
  }
  return data;
});
console.log(s);

var s is undefined! ....

Upvotes: 1

Views: 913

Answers (2)

Orelsanpls
Orelsanpls

Reputation: 23495

You are mixing up callback and Promise which are two different way to handle asynchronous calls.

I recommend you to use of Promises because they are simpler and the present and future of javascript.


Using async/await which is the next step after Promises

const user = {
 find: () => ['jon', 'kalessi', 'jorah'],
};

async function getUsers() {
  return (await user.find({})) || [];
}

async function myJob() {
  const users = await getUsers();
  
  console.log(users);

  // Put your next code here
}

myJob();


Full promise :

const user = {
  find: () => new Promise((resolve) => resolve(['jon', 'kalessi', 'jorah'])),
};

user.find({})
  .then((docs = []) => {
    console.log(docs);

    // Put you next code here, you can use of the variable docs
  })
  .catch((err) => {
    console.log(err);
  });


Full callback :

const user = {
  find: (_, callback) => callback(false, ['jon', 'kalessi', 'jorah']),
};

user.find({}, (err, docs = []) => {
  if (err) {
    console.log(err);
  } else {
    console.log(docs);

    // Put you next code here, you can use of the variable docs
  }
});

Upvotes: 3

Pushpendra Kumar
Pushpendra Kumar

Reputation: 1674

I think user.find returning the promise. you can do like this.

const nedb = require('nedb');
const user = new nedb({ filename: './builds/database/users.db', autoload: true });
var s = user.find({}, function (err,docs) {
  if(docs.length == 0) {
    var data = false;
  } else {
    var data = docs;
  }
  return data;
});

Promise.all(s)
.then(result => {
   console.log(result);
});

Otherwise you can also use await Like this:

async function abc(){
    const nedb = require('nedb');
        const user = new nedb({ filename: './builds/database/users.db', autoload: true });
    var s = await user.find({}, function (err,docs) {
      if(docs.length == 0) {
        var data = false;
      } else {
        var data = docs;
      }
      return data;
    });
}

because await worked with async thats why i put it into async function.

Upvotes: 0

Related Questions