在.then语句中更改数组(javascript)

时间:2016-06-27 06:24:55

标签: javascript arrays promise

在for for循环中,我循环遍历不同的值,我测试特定值是否返回错误。预定义函数返回promise,如果我需要它一次就可以了。但我需要一种方法来存储所有错误(错误数组)和所有正确状态(纠正数组)和我正在使用的硬件不允许动态添加文本到屏幕所以我使用数组。但我无法找到一种方法来进行。然后阻止。我在网上搜索解决方案,但找不到能解决问题的解决方案。

for (var i = 0; i < idarray.length; i++) {
  type = idarray[i];
  for (var j = 0; j < maxValues[i]; j++) {
    //console.log("Type: ",type);
    //here i send new command with type and value
    var sethbt = myLibrary.NewCommand(uuid, "Param", {
      "Data": [{
        "Type": type, //number
        "Control": 1,
        "Value": j.toString() //string
      }]
    })
    //here i read the value of type
    var hbt = myLibrary.NewCommand(uuid, "Param", {
      "Data": [{
        "Type": type,
        "Control": 0,
        "Value": ""
      }]
    })
    //hbt returns a promise where i get the value, if control==2 it is error, otherwise 
    //it is ok
    hbt.then(function(data) {
      obj = JSON.parse(data);
      if (obj[0].Control == 2) {
        var text = "ERROR: Type: \"" + obj[0].Type + "\" --> Value:\"" + obj[0].Value + "\"";
        //here i want to add error to array of errors, but change is not seen
        //out of .then block
        errors.push(text);
      } else {
        corrects.push("OK: Type: \"" + obj[0].Type + "\" --> Value:\"" + obj[0].Value + "\"");
      }

    });
  }

0 个答案:

没有答案