0

I'm having a problem with node JS.

Basically,I Have this function :

let getImageName = function(query,callback){
  Images.getImageById(query,function(err,image){
    return image.filename;
  });
}

But when i called this,the console.log() print undefined,and I know that the function getImageName is working.

app.get('/api/books/:_id', function(req, res){
Book.getBookById(req.params._id, function(err,book){
    if(err){
        throw err;
    }
    console.log(getImageName(book.cover));
});
});
Diego Oliveira
  • 121
  • 1
  • 1
  • 9

1 Answers1

0

You are trying to return a value from a callback to an asynchronous function. They don't work that way. You are treating getImageById() like it is synchronous but getImageById() is asynchronous (which is possible to infer from the way it takes a callback).

Images.getImageById(query,function(err,image){
    return image.filename;
  });

There are many solutions depending on your use case. The easiest could be to move the console.log() to inside that callback. (But if you then change the console.log() to a return statement, you will have the same problem all over again.)

If this is all confusing, there's a short explanation at https://docs.nodejitsu.com/articles/getting-started/control-flow/what-are-callbacks/.

Trott
  • 66,479
  • 23
  • 173
  • 212
  • Hi,thanks for your response,i solve this using callback. `let getImageName = function(query,callback){ Images.getImageById(query,function(err,image){ callback(image.filename); }); }` and i make the call `getImageName(book.cover,function(response){ book.cover = response; res.json(book); });` This works for me. – Diego Oliveira Jun 07 '17 at 04:48