代码之家  ›  专栏  ›  技术社区  ›  Evan Park

Javascript更改为内部变量。然后在外部找不到[重复]

  •  -1
  • Evan Park  · 技术社区  · 8 年前

    下面是我试图执行的代码。

    如评论中所述。我正在尝试使阵列1的更新在外部可见。then()函数。

    有人能帮我理解为什么会这样吗?以及如何使其在外部可见。then()函数?

    非常感谢!

    var array1 = [];    
    
    array2.forEach(function(item) {
        // this is an async all to db.collection.findOne({_id: item.id});
        object = getObject(item.id);
        object.then(function(object) {
            array1.push(object);
    
            //if I print console.log(array1) here, I can see it getting updated
        });
    });
    
    // this does not print anything
    console.log(array1)
    

    ***编辑

    虽然这是现有问题的重复, 我能够通过下面提供的示例解决此问题

    var array1 = [];    
    
    objectPromises = array2.map(item => function(item));
    
    Promise.all(objectPromises).then(objects -> {
        objects.forEach(function(object){
            array1.push(object);
        });
    
        console.log(array1);
    });
    

    谢谢你的帮助!

    1 回复  |  直到 8 年前
        1
  •  1
  •   CertainPerformance    8 年前

    你会 使用 .then (或 await ),但实施起来并不困难:

    const allPromises = array2.map(item => getObject(item.id));
    Promise.all(allPromises).then(allObjects => {
      // do something with all objects
    });