【问题标题】:How to make object variable changes remain after ForEach loop. Javascript如何在 ForEach 循环之后保留对象变量更改。 Javascript
【发布时间】:2016-12-04 19:05:12
【问题描述】:

我正在尝试使用 NodeJS 中的 mongoose 在我的 MongoDB 数据库中生成一个 Data 对象。

这是sn-p的代码:

console.log(RecipeData.ingredients);
RecipeData.spices.forEach(function(spice){
    module.exports.findSpiceByName(spice, function(err, res){
        if (err){
            return callback(err);
        }
        RecipeData.ingredients.push(res._id);
        return callback(null, RecipeData);
    });
});

console.log(RecipeData.ingredients);

基本上,我的 RecipeData 是一个具有一些属性的对象。在这种情况下,主要是香料和配料。这两个都是字符串列表。

  • 我想检查 RecipeData.spice:
    • 如果列表中有一个元素:(该元素将是香料的名称)
      • 我想在我的 Spices Collection 中找到与该名称关联的香料,并将其 _id 永久添加到我的 RecipeData.ingredients 中

在我用来测试此代码的示例中,console.log 的输出不应该相同。

知道为什么变量 RecipeData.ingredients 在 ForEach 循环之外没有改变吗?

提前感谢您的帮助。

【问题讨论】:

    标签: javascript arrays node.js object mongoose


    【解决方案1】:

    听起来像是一个异步编程问题。虽然您没有发布源代码,但我假设 module.exports.findSpiceByName 是异步的,而 forEach 不是,所以 forEach 完成并且您的第二个 console.log 在您的 findSpiceByName 调用有时间完成之前运行.

    解决此问题的一种方法是使用Promises,然后等待所有这些都完成,然后再尝试检查成分:

    var spicePromises = RecipeData.spices.map(function(spice) {
        return new Promise(function(resolve, reject) {
            module.exports.findSpiceByName(spice, function(err, res) {
               if (err) {
                  return reject(err);
               }
               resolve(res._id);
            });
        });
    });
    
    Promise.all(spicePromises).then(function(ingredients) {
      Recipe.ingredients = ingredients;
      console.log(RecipeData.ingredients);
    });
    

    【讨论】:

    • 这实际上是绝对正确的。这些console.logsfindSpiceByName 之前运行。我怎样才能解决这个问题?尽管不管控制台日志如何,我确信变量不会改变,因为我稍后会尝试将数据对象添加到集合中,但它没有根据需要进行更新。
    • 更新了我的答案,并举例说明了如何解决此问题
    • 这并没有太大帮助,因为同样的事情一直在发生。所以为了避免这个问题,我在集合已经在数据库中之后更改了数据。这样我就可以在发生更改时直接更新数据库。不过感谢您的帮助。 :)
    猜你喜欢
    • 1970-01-01
    • 2013-07-14
    • 1970-01-01
    • 2014-11-18
    • 1970-01-01
    • 1970-01-01
    • 2016-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多