首页 > 解决方案 > 使用外部模块的 JavaScript 空数组

问题描述

我对变量或与时间有关的东西有疑问。我正在迭代一个 forEach 循环,并且对于每个元素,我通过模块的函数检查其邮件是否为真。如果这封电子邮件是真的,我把它放在一个新的空数组中。问题是该数组填充了该数据,但仅在循环内。一旦循环仍然是空的,有谁知道为什么?

模块:

-npm install email-existence

现在的问题是:

var validos = [];    
sinRepetidos.forEach((element) => {
      emailExistence.check(element.Email, function (error, response) {
        var exist = false;
        // If the email is false print the email and remove from the list.
        if (response) {
          console.log(
            element.Nombre + " con email " + element.Email + " es: " + response
          );
          exist = true;
        }
        if (error) {
          console.log(error);
        }
        if (exist) {
          validos.push(element);
        }
      });
    });

包含一些数据的数组:

    [
  {
    Id: '3',
    Nombre: 'Dato3',
    Apellidos: 'Prueba Test',
    Email: 'dato3@email.com'
  },
  {
    Id: '5',
    Nombre: 'Dato5',
    Apellidos: 'Prueba Test',
    Email: 'dato5@email.com'
  },
  {
    Id: '2',
    Nombre: 'Dato2',
    Apellidos: 'Prueba Test',
    Email: 'dato2@email.com'
  },
  {
    Id: '4',
    Nombre: 'Dato4',
    Apellidos: 'Prueba Test',
    Email: 'dato4@email.com'
  }
]

标签: javascriptloopsvariablesasynchronousforeach

解决方案


推荐阅读