在数组中推送承诺,数组保持为空

Pushing promises in an array the array remains null

我在 promises =[] 数组中推送 promise,但是在传递 promise 时。如果我的代码有任何问题请回答

searchProductVariant: (start, end, combinations) => {
return new Promise((resolve,reject)=>
{
  var promises = [];
  console.log(start, "  ", end);
  for (let i = start; i < start + end; i++) {
    vv = combinations[i - start].product_variant_name.split("_");
    console.log("kk", vv);

    vv.forEach((v) => {
      sql = `SELECT id FROM ecommerce.variant_values as varval where varval.value like '${v}'`;
      pool.query(sql, [], (error, results, fields) => {
        if (error) {
          console.log("the errrror is", error);
        }
        if (results[0].id) {
          console.log("i is ", i);
          let temp = addProductVariantDetails(i, results[0].id);
          promises.push(temp
          );
        }
      });
    });
  }
  console.log(promises); //it prints null
  return Promise.all(promises)
    .then((resul) => {
      return resolve(resul);
    })
    .catch((err) => {
      return reject(err);
    });
})
}

pool.query 收到回调,这是唯一添加到 promises 数组的东西。我认为您可能只是想在任何 query 回调 return 之前 运行 Promise.all。您可能需要切换到 pool.query 的基于 Promise 的版本(如果存在的话),或者您可以像这样编写自己的版本。

searchProductVariant: (start, end, combinations) => {
  // DELETE: Original Promise wrapper. Return Promise.all result directly.
  var queries = [];  // NEW: Track queries.
  var promises = [];
  console.log(start, "  ", end);
  for (let i = start; i < start + end; i++) {
    vv = combinations[i - start].product_variant_name.split("_");
    console.log("kk", vv);

    vv.forEach((v) => {
      sql = `SELECT id FROM ecommerce.variant_values as varval where varval.value like '${v}'`;
      // NEW: Wrap pool.query to create a promise that waits for the possible add
      // to the promises array, adding the separate promises array.
      queries.push(
        new Promise((resolve, _) => {
          pool.query(sql, [], (error, results, fields) => {
            resolve([error, results, fields]);
          })
        }).then([error, results, fields] => {
          if (error) {
            console.log("the error is", error);
          }
          if (results[0].id) {
            console.log("i is ", i);
            let temp = addProductVariantDetails(i, results[0].id);
            // Keep temp in an array so we only return valid results,
            // but also return it so the returned Promise surfaces
            // any rejection issued at any time.
            promises.push(temp);
            return temp;
          }
        }));
    });
  }
  console.log(promises);
  // Wait for the queries, then wait for the promise results.
  return Promise.all(queries).then(() => Promise.all(promises));
}

您还可以通过完全删除 promises 数组并在末尾 returning Promise.all(queries) 来简化此代码;但是,您需要过滤掉来自任何 queries 承诺的 undefined 结果,这些承诺会导致错误或无 ID 结果,而且我对您的代码了解不多,无法知道 undefined可以适当过滤。 (您也没有检查 results.length > 0,但是因为您拥有它,所以无论哪种方式都会导致 Promise 被拒绝。)