功能结果无法在范围之外访问

时间:2016-04-01 18:24:06

标签: javascript node.js express

我有一个可以正常工作并将数据正确返回console.log的函数。然后我如何将此函数包装起来并调用它,根据需要检索数据?我没有运气就尝试了以下内容。

所有这些代码都有效:

function weekendPlans() {
  Entry.aggregate(
      [
          { "$redact": {
              "$cond": {
                  "if": {
                      "$or": [
                          { "$eq": [ { "$dayOfWeek": "$selectedDate" }, 1 ] },
                          { "$eq": [ { "$dayOfWeek": "$selectedDate" }, 6 ] },
                          { "$eq": [ { "$dayOfWeek": "$selectedDate" }, 7 ] }
                      ]
                  },
                  "then": "$$KEEP",
                  "else": "$$PRUNE"
              }
          }}
      ],
      // GET THE RESULTS AND RETURN IF selectedDate MATCHES THIS WEEKEND
      function(err,results) {
        if (err) throw err;
        //console.log(results);
        var i = results.length;
        var theWeekend;

        while(i--) {
          if(results[i].selectedDate === friday || saturday || sunday) {
              theWeekend = results[i];
              break;
          }
        }
        console.log(theWeekend);
      }
)};

调用范围之外的函数会返回undefined

console.log(weekendPlans());

预期结果:

{ _id: 56fe9fe71f84acc2564b9fe8,
  url: 'http://www.timeoutshanghai.com/features/Blog-Food__Drink/35271/Baristas-showcase-latte-art-in-Shanghai.html',
  title: 'TIMEOUT',
  selectedDate: Sat Apr 02 2016 01:00:00 GMT+0100 (BST),
  __v: 0 }

1 个答案:

答案 0 :(得分:2)

因为这是一个异步操作,所以您需要重新思考实现函数的方式。借用Node的事件驱动模型,添加一个回调函数:

function weekendPlans(callback) {
                      // ^ this is the magic param
  Entry.aggregate(
      [
          { "$redact": {
              "$cond": {
                  "if": {
                      "$or": [
                          { "$eq": [ { "$dayOfWeek": "$selectedDate" }, 1 ] },
                          { "$eq": [ { "$dayOfWeek": "$selectedDate" }, 6 ] },
                          { "$eq": [ { "$dayOfWeek": "$selectedDate" }, 7 ] }
                      ]
                  },
                  "then": "$$KEEP",
                  "else": "$$PRUNE"
              }
          }}
      ],
      // GET THE RESULTS AND RETURN IF selectedDate MATCHES THIS WEEKEND
      function(err,results) {
        // if (err) throw err;
        // we don't need to throw an error here, we'll pass it in the cb function
        //console.log(results);
        var i = results.length;
        var theWeekend;

        while(i--) {
          if(results[i].selectedDate === friday || saturday || sunday) {
              theWeekend = results[i];
              break;
          }
        }
        callback(err, theWeekend)
        // ^ call the callback
      }
)};

然后像这样使用它:

weekendPlans(function(err, theWeekend) {
    if (err) throw err
    // now you can check for err and reference theWeekend
})