【问题标题】:while loop and callback return different resultswhile 循环和回调返回不同的结果
【发布时间】:2016-07-22 19:46:35
【问题描述】:

我有一个匹配条件的 while 循环来过滤来自 mongodb 的数据。但是,当我使用回调时,我只收到console.log 的一个结果。如果我在 while 循环中使用 console.log,我应该会收到三个条目。为什么只有一条数据进入回调?

while(i--) {
  if (0 >= [friday, saturday, sunday].indexOf(results[i].selectedDate)) {
      theWeekend = results[i];
      console.log(theWeekend); //returns three results (correct)
    }
}
callback(err, theWeekend)
console.log(theWeekend); //returns one results (incorrect)

正确的数据

{ _id: 56fffb5ceb76276c8f39e3f3,
  url: 'http://londonist.com/2015/11/where-to-eat-and-drink-in-balham',
  title: 'Where To Eat And Drink In... Balham  | Londonist',
  selectedDate: Fri Apr 01 2016 01:00:00 GMT+0100 (BST),
  __v: 0 }
{ _id: 56fffb8eeb76276c8f39e3f5,
  url: 'https://news.ycombinator.com/item?id=11404770',
  title: 'The Trouble with CloudFlare | Hacker News',
  selectedDate: Sun Apr 03 2016 01:00:00 GMT+0100 (BST),
  __v: 0 }
{ _id: 56fffb6ceb76276c8f39e3f4,
  url: 'http://wellnessmama.com/13700/benefits-coconut-oil-pets/',
  title: 'Benefits of Coconut Oil for Pets - Wellness Mama',
  selectedDate: Sat Apr 02 2016 01:00:00 GMT+0100 (BST),
  __v: 0 }

数据不正确

{ _id: 56fffb6ceb76276c8f39e3f4,
  url: 'http://wellnessmama.com/13700/benefits-coconut-oil-pets/',
  title: 'Benefits of Coconut Oil for Pets - Wellness Mama',
  selectedDate: Sat Apr 02 2016 01:00:00 GMT+0100 (BST),
  __v: 0 }

【问题讨论】:

标签: javascript node.js express while-loop


【解决方案1】:

您需要使用一个数组来存储所有结果,如下所示:

var theWeekends = []
while(i--) {
  if (0 >= [friday, saturday, sunday].indexOf(results[i].selectedDate)) {
      theWeekends.push(results[i]);

    }
}
callback(err, theWeekends)
console.log(theWeekends); //returns 3 results (correct)

【讨论】:

    猜你喜欢
    • 2013-12-18
    • 2019-06-07
    • 2021-09-24
    • 1970-01-01
    • 2018-12-03
    • 2013-10-27
    • 1970-01-01
    • 1970-01-01
    • 2011-08-18
    相关资源
    最近更新 更多