Undefined return value from the function call Javascritpt

Move the following line:

res.render("index.html", content);

into the hasNextPage callback:

functions.getRecentPost = function ( req, res, next ) {

  //.........

  es.search(query, function (err, data) {

    //.........

    hasNextPage(_page, content.posts.length, function (data) {

      content.hasNext = data;
      res.render("index.html", content);

    });
  });
};

If you expect getRecentPost to return something then you need to add a callback to it as well so that you can use it’s return value. For example, if you expect to be doing this:

functions.getRecentPost = function ( req, res, next) {

  //......

  return content;
}

doSomething(functions.getRecentPost(x,y,z));

It won’t work because the final value of content will be retrieved asynchronously. Instead you need to do this:

functions.getRecentPost = function ( req, res, next, callback ) {

  //.........

  hasNextPage(_page, content.posts.length, function (data) {

    content.hasNext = data;
    res.render("index.html", content);

    callback(content);

  });
};

functions.getRecentPost(x,y,z,function(content){
  doSomething(content);
})

You cannot return data asynchronously. You need to change your code (and your thinking) from writing stuff like this:

asyncFunction(function(data){
    foo = data;
});

doSomething(foo);

into this:

asyncFunction(function(data){
    doSomething(data);
});

Basically, move all the code that you would want to run after the async function into the callback function you passed into it.

Regular imperative code looks like this:

function fN () {
  x = fA();
  y = fB(x);
  z = fC(y);
  return fD(fE(z));
}

asynchronous code looks like this:

function fN (callback) {
  fA(function(x){
    fB(x,function(y){
      fC(y,function(z){
        fE(z,function(zz){
          fD(zz,function(zzz){
            callback(zzz);
          });
        });
      });
    });
  });
}

Notice that you don’t return, you pass in a callback instead.

Leave a Comment