首页 > 解决方案 > 为什么我的 Promise.all().then() 在所述 Promise.all() 中的承诺之前执行

问题描述

我正在尝试在循环内的快速查询中的数组中添加一些值,并且我想在所述循环之外获取该数组。

app.get("/getMatchedProfile",function (req,res) {
   con.query("SELECT\n" +
       "\tidUser2\n" +
       "FROM\n" +
       "\t`match`\n" +
       "WHERE\n" +
       "\tidUser1 = ?", [req.query.id], function (error, results) {
      if (error) throw error;
      let taille = results.length;
      let arrayPromise = [];//array of queries
      let arrayMatch = [];//the array i want to retreive
      console.log(taille);
      for (let i = 0; i < taille; i++) {
         arrayPromise.push(con.query("SELECT idUser1, idUser2 FROM `match` WHERE idUser1 = ?", [results[i].idUser2],
             function (error, results) {
                if (error) throw error;
                for (let j = 0; j < results.length; j++) {
                   if (results[j].idUser2 == req.query.id) {
                      arrayMatch.push(results[j].idUser1);
                      console.log("1111 : "+arrayMatch)//should print first
                   }
                }
             }
         )
         )
      }
      Promise.all(arrayPromise).then(function() {
           console.log("22222 : " + arrayMatch);//should print 2nd + not empty
          }
      );
   });

});

首先打印“22222”,然后打印“11111”,应该是相反的位置

标签: javascriptnode.jsexpresspromise

解决方案


推荐阅读