0

Hello I am new to promises and callbacks in node js I am doing something to fetch users list using another function using callbacks but getting fail. somewhere I found to use promises. but never used promises. can anyone help me with code?

send_noti('12', function(res){

    console.log(res);
});

function send_noti(value, callback){

    connection.query(" SELECT * from users ", function( err, res ){

        callback( res );
    });
}
iam
  • 973
  • 4
  • 11
  • 21

2 Answers2

0

You're looking for something like this:

function sendNotiAsync(value) {
  return new Promise((resolve, reject) => // Promise constructor
    connection.query("SELECT * from users", (err, data) => // Perform the action
      err ? reject(err) : resolve(data))); // If error exists, reject, else resolve
}

And use it like this:

sendNotiAsync(someValue)
  .then(data => {
    // Work with data here, for example
    console.log(data);
  })
  .catch(err => {
    // Handle errors here
    console.error(err);
  });
t.niese
  • 39,256
  • 9
  • 74
  • 101
Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
0

In node callbacks of async functions should always have the signature function(err, result /*,...*/)

Your example should look like:

 send_noti('12', function(err, res) {
   if( !err ) {
     console.log(res);
   }
 });

 function send_noti(value, callback) {
   connection.query(" SELECT * from users ", callback );
 }

Beside that your example does not use Promises. With Promises it would look like this:

send_noti('12')
  .then(function(res) {
     console.dir(res)
  })
  .catch(function(err) {
     console.dir(err)
  })

function send_noti(value, callback) {
  return new Promise(function(resolve, reject) {
    try {
      connection.query(" SELECT * from users ", function(err, res) {
        if (err) {
          reject(err);
        } else {
          resolve(res);
        }
      });
    } catch (err) {
      reject(err);
    }
  })
}
t.niese
  • 39,256
  • 9
  • 74
  • 101
  • but it seems that connection.query(); not executing. means no result. no console. – iam Apr 11 '16 at 07:29
  • @iam I added a _try-catch_ block, and `console.dir`in the `.catch` callback, now you should definitly see an error telling you what went wrong. – t.niese Apr 11 '16 at 07:34