为什么Promise.all()。then()仍然使输出同步?

时间:2017-08-31 11:05:06

标签: javascript asynchronous

我正在研究Javascript,重点是让一切都以异步方式运行。练习是这样的:要有一个用随机数填充的数组。然后,该数组的max元素将是矩形2D数组的长度。对于要在2D数组中用作索引的数组中的每个唯一元素,我必须找到2D数组中行和列的总和,以及2D中的周围元素的总和。阵列。这些任务需要单独完成,我使用Promises。但是当我登录控制台以查看工作是如何进行的时,它仍然会同步输出它,甚至更糟糕的是它甚至在填充之前就开始搜索阵列。我是新手,所以我需要一些指导。

var arrayA = [];
var matricaA = [];
var n=10;
var m;
var arr = [];
var k = 0;
var funcMatrixHolder = [];
var result = [];

function genRandomNum(min,max)
{
    return Math.floor(Math.random()*(max-min+1)+min);
}

function fillArray(n) {
  return new Promise(function(resolve,reject) {
    arrayA = Array.from({length: n}, () => genRandomNum(1,10));
    m = arrayA[0];
    arrayA.filter(function(pos){
      if(pos > m) {
        m = pos;
      }
      resolve(m);
    });
  });
}

function createMatrix(size) {
  return new Promise(function(resolve, reject){
    arr = Array.from({length: size}, () => genRandomNum(1,10));
    //console.log(arr);
    resolve(arr);
  });
}

function sumRowCol(matrix, len, arr) {
  return new Promise(function(resolve, reject) {
    var shuma=0;
      arr.filter(function(elem, pos) {
      var poz = elem-1;
        if(arr.indexOf(elem) === pos) { //per cdo element unik
          for(var k = 0; k<len; k++){
            sum+=matrix[k][poz];
            sum+=matrix[poz][k];
            //console.log(k);
            //
            }
          }
          resolve(sum);
          console.log(sum+" sum"); //to check how it works
          sum=0;
      })
  });
}

function sumNr(myArray, arr) {
  return new Promise(function(resolve, reject){
    var sum = 0;
      arr.filter(function(elem, pos) {
      var rowLimit = myArray.length-1;
      var columnLimit = myArray[0].length-1;
      var i = elem-1;
      var j = elem-1
      if(arr.indexOf(elem) === pos) { //per cdo element unik
            for(var x = Math.max(0, i-1); x <= Math.min(i+1, rowLimit); x++) {
              for(var y = Math.max(0, j-1); y <= Math.min(j+1, columnLimit); y++) {
                if(x !== i || y !== j) {
                  sum += myArray[x][y];
                  //
                }
              }
            }
            console.log(sum + "sum");
            resolve(sum);
            sum = 0;
          }

        })
  })
}

fillArray(n).then(function(result) {
  //filled array and got it's max
});

while(k<m) {
  funcMatrixHolder.push(createMatrix(m));
  k++;
}

//console.log(funcMatrixHolder);

Promise.all(funcMatrixHolder).then(function(result) {
  matricaA = result;
});


Promise.all([sumNr(matricaA,arrayA),sumRowCol(matricaA,m,arrayA)]).then(function(result){
    console.log(result);
});

1 个答案:

答案 0 :(得分:0)

以防万一,这是得到批准的答案: (原谅非英文标签)

var arrayA = [];
var matricaA = [];
var n=10;
var m;
var arr = [];
var k = 0;
var funcMatrixHolder = [];
var result_final = [];
var filterArr = [];
var result_final_final = [];

function genRandomNum(min,max)
{
    return Math.floor(Math.random()*(max-min+1)+min);
}

function fillArray(n) {
  return new Promise(function(resolve,reject) {

    arrayA = Array.from({length: n}, () => genRandomNum(1,10));
    m = arrayA[0];
    arrayA.filter(function(elem, pos){
      if(elem > m) {
        m = elem;
      }
      if(arrayA.indexOf(elem) === pos) {
        filterArr.push(elem);
      }
    });
    var fArrPH = {
      max: m,
      fArr: filterArr
    }
    resolve(fArrPH);
  });
}

function createMatrix(size) {
  return new Promise(function(resolve, reject){

    arr = Array.from({length: size}, () => genRandomNum(1,10));
    //console.log(arr);
    resolve(arr);

  });
}

function fillArrayFunction(size) {
  return new Promise(function(resolve, reject) {
    for (var i=0; i<size; i++){
      funcMatrixHolder.push(createMatrix(size));
    }
    resolve(funcMatrixHolder);
  })
}



function shumaRreshtKolone(matrix, index, madhesia) {
          let shuma=0;
          //console.log(madhesia);
          for(var k = 0; k<madhesia; k++){
            //console.log(index);
            //index = 10;
            shuma+=matrix[k][index];
            shuma+=matrix[index][k];

            }
           console.log("ShumaRreshtKolone u llogarit.");
          return shuma;
}

function sumNrRrethues(myArray, index) {
     var sum = 0;
      var rowLimit = myArray.length-1;
      var columnLimit = myArray[0].length-1;
      var i = index-1;
      var j = index-1
            for(var x = Math.max(0, i-1); x <= Math.min(i+1, rowLimit); x++) {
              for(var y = Math.max(0, j-1); y <= Math.min(j+1, columnLimit); y++) {
                if(x !== i || y !== j) {
                  sum += myArray[x][y];
                }
              }
            }
            console.log("ShumaNrRrethues u llogarit");
            return sum;
}

var m1;
function job() {
return new Promise(function(resolve,reject) {
    fillArray(n).then(function(result) {
       //console.log("array", result);
        m1 = result;
        return fillArrayFunction(result.max);
    }).then(function(result) {
      Promise.all(result).then(function(result) {
        matricaA = result;
        console.log(matricaA);
        console.log(arrayA);
        m1.fArr.map(function(item) {
           //console.log("item", item);
          return result_final.push({
            Elementi: m1.fArr.indexOf(item),
            ShumaRreshtKolone: shumaRreshtKolone(matricaA,item-1,m1.max),
            ShumaNrRrethues: sumNrRrethues(matricaA, item-1)
          });
        });
        resolve(result_final);
      }).catch(err => {
        reject(err);
      })
    })
  })
}

job().then(function(result){
  console.log(JSON.stringify(result));
}).catch(err => {
  console.log(err);
})