C
C
Crash2016-10-23 14:35:48
Node.js
Crash, 2016-10-23 14:35:48

How can I make this callback code return a boolean?

I want to make this function return a boolean value (true - if the entry in the table is found, false otherwise):

function existsEntry(postId){
  db.serialize(function(){
    db.get("SELECT * FROM posts WHERE post_id = ?", [postId], function(err, row){
      if (err) throw err;
            console.log(row);
    });

    db.close();
  });
}

console.log(existsEntry("21706"));

But it's expected to print undefined anyway. How to change her work? I am new to Node

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2016-10-23
@Bandicoot

No way.
The only thing that an asynchronous function can return is a Promise, that is, a promise that some value will be received at some point in time.

function existsEntry(postId){
  return new Promise(function (resolve, reject) {
    db.serialize(function(){
      db.get("SELECT * FROM posts WHERE post_id = ?", [postId], function(err, row){
        if (err) {
          resolve(false); // или reject()
        } else {
          resolve(true);
        }
      });

      db.close();
    });
  });
}

existsEntry("21706").then(function (answer) {console.log(answer)});

As soon as you have an asynchronous function, all other code that works with it must also become asynchronous, and you can forget the words "return the result of the function"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question