来自函数调用Javascript的未定义返回值

时间:2013-07-04 01:24:06

标签: javascript node.js scope undefined

我正在尝试获取返回值,但始终未定义。

        var hasNext;
         es.search(nextQuery, function (err, data) {
            if(data.hits.hits.length) {
              return hasNext = true;
            }
            return hasNext = false;
        });

我不知道如何获得任何返回值并在其他地方使用它?我需要使用任何这个返回值来验证其他函数,但它似乎在范围或其他东西。

这是我的代码:

functions.getRecentPost = function ( req, res, next ) {
    ......... 
    // This will get all the post
es.search(query, function (err, data) {
    if(err) { // if error means no post and redirect them to create one
        return res.redirect('/new/post');
    }

              ....
    content.hasPrevious = hasPreviousPage(_page, content.posts.length); // this function is okay

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

            content.hasNext = data;

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



function hasNextPage (pageNum, totalPost, callback) {

    es.search(query, function (err, data) {
        if(data.hits.hits.length) {
        return callback(true);
        }
        return callback(false);
    });
};

1 个答案:

答案 0 :(得分:1)

移动以下行:

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

进入hasNextPage回调:

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);

    });
  });
};

如果您希望getRecentPost返回某些内容,那么您还需要为其添加一个回调,以便您可以使用它的返回值。例如,如果您希望这样做:

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

  //......

  return content;
}

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

它不会起作用,因为内容的最终值将被异步检索。相反,你需要这样做:

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);
})

您无法异步返回数据。你需要改变你的代码(和你的想法)来写这样的东西:

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

doSomething(foo);

进入这个:

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

基本上,将您希望在异步函数之后运行的所有代码移动到传递给它的回调函数中。

常规命令式代码如下所示:

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

异步代码如下所示:

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

请注意,您不会返回,而是传入回调。

相关问题