【问题标题】:Variable Scope in nodejs misunderstandingnodejs中的变量范围误解
【发布时间】:2015-11-04 06:32:00
【问题描述】:

我很难理解为什么从另一个函数返回一个数组只限于一个代码块。即:

exports.join = function(req, res){
  User.findById(req.user._id, function(err, user) {
     var dupe = []; //placeholder array
     var arr = user.forms_container.joinList;
     var title = user.forms_container.title;
     arr.forEach(function (rep) {
      //console.log(rep);
      Report.findById(rep).deepPopulate('subreport.subreport.subreport.subreport.subreport.subreport').execAsync()
      .then(function(doc) {
        //console.log(doc);
        dupe.push(doc);
        treeCycle(doc, dupe);
        console.log(dupe);
      }).catch(function(err) {
        throw err;
      });
      tracker = tracker + 1;

      if(tracker == arr.length) {
        console.log(dupe); //returns [];
        var counter = 0;
        var masterbody;
        for(var x = 0; x < dupe.length; x++) {
           masterbody = masterbody + dupe[x].body;
           counter = counter + 1;
        }
        if(counter==dupe.length) {
          newDoc.body = masterbody;
          //newDoc.save();
          res.json(newDoc);
        }
      }
     });

  });
};

有一次,我调用treeCycle,它会遍历那个函数(递归函数)并开始填充数组“dupe”,如果我马上在控制台中记录它,它显示它正在完成,这里是控制台c/p'd:

[ { _id: 55c35cd942dd12ec19b30f2e,
    owner: 55a80b8404dc0dc8187395d8,
    title: 'Chrome1',
    date: 'Thu Aug 06 2015 09:10:49 GMT-0400 (Eastern Daylight Time)',
    body: '123213',
    __v: 0,
    isCompleted: false,
    subreport: [],
    authors: [ 'Karan Kotwal' ],
    author: [ 55a80b8404dc0dc8187395d8 ] } ]
[ { _id: 55c35cd942dd12ec19b30f2e,
    owner: 55a80b8404dc0dc8187395d8,
    title: 'Chrome1',
    date: 'Thu Aug 06 2015 09:10:49 GMT-0400 (Eastern Daylight Time)',
    body: '123213',
    __v: 0,
    isCompleted: false,
    subreport: [],
    authors: [ 'Karan Kotwal' ],
    author: [ 55a80b8404dc0dc8187395d8 ] },
  { _id: 55c8d774e904bc141681e115,
    body: 'dddd',
    owner: 55a80b8404dc0dc8187395d8,
    date: 'Mon Aug 10 2015 12:55:16 GMT-0400 (Eastern Daylight Time)',
    title: 'herdrute',
    __v: 1,
    isCompleted: false,
    subreport: [],
    authors: [ 'Karan Kotwal' ],
    author: [ 55a80b8404dc0dc8187395d8 ] } ]
[ { _id: 55c35cd942dd12ec19b30f2e,
    owner: 55a80b8404dc0dc8187395d8,
    title: 'Chrome1',
    date: 'Thu Aug 06 2015 09:10:49 GMT-0400 (Eastern Daylight Time)',
    body: '123213',
    __v: 0,
    isCompleted: false,
    subreport: [],
    authors: [ 'Karan Kotwal' ],
    author: [ 55a80b8404dc0dc8187395d8 ] },
  { _id: 55c8d774e904bc141681e115,
    body: 'dddd',
    owner: 55a80b8404dc0dc8187395d8,
    date: 'Mon Aug 10 2015 12:55:16 GMT-0400 (Eastern Daylight Time)',
    title: 'herdrute',
    __v: 1,
    isCompleted: false,
    subreport: [],
    authors: [ 'Karan Kotwal' ],
    author: [ 55a80b8404dc0dc8187395d8 ] },
  { _id: 55bf7465c60c959015dee0ed,
    owner: 55a80b8404dc0dc8187395d8,
    title: 'ffefeeffefeeffefefe',
    date: 'Mon Aug 03 2015 10:02:13 GMT-0400 (Eastern Daylight Time)',
    body: 'efefefefef',
    __v: 0,
    isCompleted: false,
    subreport: [],
    authors: [ 'Karan Kotwal' ],
    author: [ 55a80b8404dc0dc8187395d8 ] } ]
[ { _id: 55c35cd942dd12ec19b30f2e,
    owner: 55a80b8404dc0dc8187395d8,
    title: 'Chrome1',
    date: 'Thu Aug 06 2015 09:10:49 GMT-0400 (Eastern Daylight Time)',
    body: '123213',
    __v: 0,
    isCompleted: false,
    subreport: [],
    authors: [ 'Karan Kotwal' ],
    author: [ 55a80b8404dc0dc8187395d8 ] },
  { _id: 55c8d774e904bc141681e115,
    body: 'dddd',
    owner: 55a80b8404dc0dc8187395d8,
    date: 'Mon Aug 10 2015 12:55:16 GMT-0400 (Eastern Daylight Time)',
    title: 'herdrute',
    __v: 1,
    isCompleted: false,
    subreport: [],
    authors: [ 'Karan Kotwal' ],
    author: [ 55a80b8404dc0dc8187395d8 ] },
  { _id: 55bf7465c60c959015dee0ed,
    owner: 55a80b8404dc0dc8187395d8,
    title: 'ffefeeffefeeffefefe',
    date: 'Mon Aug 03 2015 10:02:13 GMT-0400 (Eastern Daylight Time)',
    body: 'efefefefef',
    __v: 0,
    isCompleted: false,
    subreport: [],
    authors: [ 'Karan Kotwal' ],
    author: [ 55a80b8404dc0dc8187395d8 ] },
  { _id: 55c361705d00464419a1d40c,
    owner: 55a80b8404dc0dc8187395d8,
    title: 'IE11',
    date: 'Thu Aug 06 2015 09:30:24 GMT-0400 (Eastern Daylight Time)',
    body: 'PEWPEWPEWPW',
    __v: 1,
    isCompleted: false,
    subreport:
     [ { _id: 55ca4d5456f8cdb416d36092,
         body: 'testest',
         owner: 55a80b8404dc0dc8187395d8,
         date: 'Tue Aug 11 2015 15:30:28 GMT-0400 (Eastern Daylight Time)',
         title: 'Sub1',
         __v: 2,
         parentReport: 55c361705d00464419a1d40c,
         isCompleted: false,
         subreport: [Object],
         authors: [Object],
         author: [Object] } ],
    authors: [ 'Karan Kotwal' ],
    author: [ 55a80b8404dc0dc8187395d8 ] },
  { _id: 55ca4d5456f8cdb416d36092,
    body: 'testest',
    owner: 55a80b8404dc0dc8187395d8,
    date: 'Tue Aug 11 2015 15:30:28 GMT-0400 (Eastern Daylight Time)',
    title: 'Sub1',
    __v: 2,
    parentReport: 55c361705d00464419a1d40c,
    isCompleted: false,
    subreport:
     [ { _id: 55ca53728ecc9400150610b6,
         body: 'sadsadasdasdasdadasdsadasdasEnter subreport here',
         owner: 55a80b8404dc0dc8187395d8,
         date: 'Tue Aug 11 2015 15:56:34 GMT-0400 (Eastern Daylight Time)',
         title: 'Sub1\'s sub1',
         __v: 1,
         parentReport: 55ca4d5456f8cdb416d36092,
         isCompleted: false,
         subreport: [],
         authors: [Object],
         author: [Object] } ],
    authors: [ 'Jeff The man' ],
    author: [ 55ad14bac2419660021d80b0 ] },
  { _id: 55ca53728ecc9400150610b6,
    body: 'sadsadasdasdasdadasdsadasdasEnter subreport here',
    owner: 55a80b8404dc0dc8187395d8,
    date: 'Tue Aug 11 2015 15:56:34 GMT-0400 (Eastern Daylight Time)',
    title: 'Sub1\'s sub1',
    __v: 1,
    parentReport: 55ca4d5456f8cdb416d36092,
    isCompleted: false,
    subreport: [],
    authors: [ 'Empty Empty' ],
    author: [ 55bbbc20877f48a01bf0c8d9 ] } ]

但是,如果这样做,为数组 dupe 的最终版本调用控制台会返回空。我在 if(tracker == array.length); 块中执行此操作,我认为它的范围将贯穿整个函数,因为我在开始时对其进行了初始化。

树循环:

function treeCycle(doc, arr) {
  if(doc.subreport.length != 0) {
    for (var x = 0; x < doc.subreport.length; x++){
      arr.push(doc.subreport[x]);
      //console.log(arr);
      if(doc.subreport[x].subreport.length != 0) {
        treeCycle(doc.subreport[x], arr);
      }
    }
  }
  else {
    return arr;
  }
};

【问题讨论】:

  • 您正在向异步函数内的数组推送,并尝试在 then() 的异步回调之外记录这些更改
  • 我没有在问题中看到任何 ES6?
  • 你不能在这样的循环中使用 Promise。查看Promise.all。

标签: javascript arrays node.js loops promise


【解决方案1】:

这似乎是一个异步问题,您的 if(tracker == arr.length) { 部分在树循环之前运行。完成异步任务后,您需要调用 if(tracker == arr.length) { 部分。

例子:

exports.join = function(req, res) {
    User.findById(req.user._id, function(err, user) {
        var dupe = []; //placeholder array
        var arr = user.forms_container.joinList;
        var title = user.forms_container.title;
        arr.forEach(function(rep) {
            //console.log(rep);
            Report.findById(rep).deepPopulate('subreport.subreport.subreport.subreport.subreport.subreport').execAsync()
                .then(function(doc) {
                    //console.log(doc);
                    dupe.push(doc);
                    treeCycle(doc, dupe);
                    console.log(dupe);

                    tracker = tracker + 1;

                    if (tracker == arr.length) {
                        console.log(dupe); //returns [];
                        var counter = 0;
                        var masterbody;
                        for (var x = 0; x < dupe.length; x++) {
                            masterbody = masterbody + dupe[x].body;
                            counter = counter + 1;
                        }
                        if (counter == dupe.length) {
                            newDoc.body = masterbody;
                            //newDoc.save();
                            res.json(newDoc);
                        }
                    }

                }).catch(function(err) {
                    throw err;
                });
        });

    });
};

【讨论】:

  • 如果我想按顺序执行,treeCycle 将在哪里完成它的循环,然后移动到下一个元素和 treeCycle 上,你会推荐它吗?
  • 我个人只是使​​用回调模式。但两者都可以正常工作。
【解决方案2】:

这很可能是您如何使用promises 的问题。我建议您阅读它们以了解它们是如何工作的,以及您应该如何重构代码以更好地使用它们。

如果您将 if (tracker... 块移动到 .then( 回调(或另一个 .then)中,它可能会起作用。

【讨论】:

    猜你喜欢
    • 2014-08-29
    • 2015-08-20
    • 2018-12-26
    • 1970-01-01
    • 2013-03-12
    • 2017-02-10
    • 1970-01-01
    • 1970-01-01
    • 2020-02-29
    相关资源
    最近更新 更多