0

I am pushing the promises in promises =[] array but when passing the promises in promises. All the array remains null which resolves and send null result if my code has any issue please answer

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);
    });
})
}
5
  • What is this code supposed to do? Also, this doesn't look like the full code. Please post a minimal reproducible example. Commented Nov 15, 2021 at 10:17
  • this is the complete code the addProductVariantDetails functions returns a promise return a promise Commented Nov 15, 2021 at 10:49
  • Where is this function called? What are the possible inputs? What is the expected output? Commented Nov 15, 2021 at 10:52
  • The expected output is the message from the database when rows are added successfully in the database or the error message if there is some error. the addProductVariantDetails in saving the variant detail in the database and returns a promise it. this function is calling multiple times and thus pushing it into an array. passing that array in promise.all should wait until all promises resolves and pass the result Commented Nov 15, 2021 at 11:02
  • There's some obvious problems with this code, but have you considered looked for a promise/async/await-enabled client for your database? Commented Nov 19, 2021 at 19:23

1 Answer 1

1

pool.query receives a callback, and that's the only thing that adds to the promises array. I think it's likely that you're just trying to run Promise.all before any of the query callbacks return. You might need to switch to a Promise-based version of pool.query, if one exists, or you can write your own like this.

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

You could also simplify this code by dropping the promises array entirely and simply returning Promise.all(queries) at the end; however, you'd need to filter out the undefined results that come from any queries promises that result in errors or ID-less results, and I don't know enough about your code to know whether undefined can be properly filtered. (You also don't check that results.length > 0, but as you have it that would result in a Promise rejection either way.)

Sign up to request clarification or add additional context in comments.

4 Comments

"You could also simplify this code by replacing the promises.push(temp) with return temp" - that's not just a simplification, it's actually a correction. The code as written currently will cause an unhandled promise rejection error (which can crash the process), if one of the temp promises returned by addProductVariantDetails do reject before all the queries are fulfilled. (And also if any of the queries rejects). Please fix that as you suggested.
@Bergi Oh, I'd written that bit about resolving before removing the outer promise constructor, but forgot to remove the description. That said, I don't see where the unhandled promise rejection would come from other than if pool.query itself throws synchronously. If addProductVariantDetails either rejects or throws it will manifest as the overall return value rejecting, so nothing is unhandled.
The problem is that the rejection only manifests as the overall return value once the second Promise.all has run - which happens only once all queries fulfill. If any of the temp promises rejects before that, it has no .then() handlers set up yet, and will be causing an unhandled rejection error.
@Bergi Here, if it'll make you happy, I'll return temp but also keep the pushed promises since the OP hasn't told us whether undefined is a valid promise resolution value. It's a little less efficient to duplicate queries and promises, but only a tiny bit, and keeps my code from functionally diverging from the OP's.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.