0

我在 promises =[] 数组中推动承诺,但是在承诺中传递承诺时。如果我的代码有任何问题,所有数组都保持为空,它会解析并发送空结果请回答

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);
    });
})
}
4

1 回答 1

1

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

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数组并Promise.all(queries)在最后简单地返回来简化此代码;但是,您需要过滤掉undefined来自任何queries会导致错误或无 ID 结果的承诺的结果,而且我对您的代码知之甚少,无法知道是否undefined可以正确过滤。(你也没有检查那个results.length > 0,但是你有它会导致 Promise 被拒绝。)

于 2021-11-19T19:21:41.877 回答