在promise nodejs之后,值被取消定义

时间:2017-07-24 19:22:09

标签: node.js

我的代码遇到了问题...我向我的数据库发出查询,检查数据库中是否存在mac数组的mac地址。如果我有任何结果,我会返回我的数据库中的mac数量,如果是> 0然后我不添加任何因为mac已经列出,但如果我的result.count = 0,那么我将添加一条新记录。

我的新记录只有mac地址。为此,我正在尝试:

var countRepetidos = 0
var countPromises = []

if (obj.data.list != {} && obj.data.list.length > 0) {
  var aux = obj.data["list"]
  countRepetidos = 0

  for (var i = 0; i < aux.length; i++) {
    countPromises.push(Database.Probing.getMacAdress(aux[i]).then(function(data) {
      console.log("probing countPromises aux[i] ", aux[i])

      if (data.count > 0) {
        countRepetidos += 1
      } else {
        Database.Probing.addMac(aux[i])
      }

      return Promise.resolve()
    }))
  }

  Promise.all(countPromises).then(() => {
    dataRepeated = [obj.data.stats.since, countRepetidos]
    listaRepeated.push(dataRepeated)

    console.log("probing listaRepeated --> ", listaRepeated)

    if (listaRepeated != [] && (listaRepeated[0][0] != undefined && listaRepeated[0][1] != undefined)) {
      Database.Probing.getLastTimestamp("probing_repeated", device.id).then(function(data) {
        var lastTimestamp = data.date_part

        console.log('probing lastTimestamp ', lastTimestamp * 1000)

        if (lastTimestamp != listaRepeated[0][0] / 1000) {
          Controllers.Agregate.agregateData("probing_repeated", 5 * 60, listaRepeated, dbHistConnectionString, device.id, device.network_id, device.organization_id, ["time", "clients"])
        }
      })
    }
  })
}

问题出现在Database.Probing.getMacAddress之后,我的aux [i]未定义,我需要将此值插入到我的数据库中。

任何人都可以提供帮助吗?

1 个答案:

答案 0 :(得分:1)

您需要保留i的值。你可以这样做:

for (var i = 0; i < aux.length; i++) {
  (function(i) {
    countPromises.push(
      Database.Probing.getMacAdress(aux[i]).then(function(data) {
        console.log("probing countPromises aux[i] ", aux[i])
        if (data.count > 0) {
          countRepetidos += 1
        } else {
          Database.Probing.addMac(aux[i])
        }

        return Promise.resolve()
      }))
  })(i)
}

修改1:根据@lain的建议,使用let而不是var

 for (let i = 0; i < aux.length; i++) {}