0

I have a list of company and would like to calculate a total amount of invoices issued to each company. The following is the code that I wrote. (Actual logic is more complicated within the loop but took them out here)

Basically I want to alert the message once the business logic within the loop is complete (Again, it will do something more complex here). I got a feeling that I can resolve this issue by using Promises but am not quite sure how to use it. I didn't quite follow Parse.com's document. I have been stuck with this for a few hours. Please help!

function calculate(companies) {

    companies.forEach(function(company) {

        var total = 0;

        var invoice = Parse.Object.extend('Invoice');
        var query = new Parse.Query(invoice);
        query.equalTo('invoiceCompany', company);

        query.find().then(function(invoices) {

            invoices.forEach(function(invoice) {

                total += parseFloat(invoice.get('amount'));

            });

        });
    });

    alert("Calculated Finished");
}

1 Answer 1

2

You can use promises in paralell:

https://parse.com/docs/js/guide#promises-promises-in-parallel

It would be something like this:

function calculate(companies) {
  var promises = [];
  companies.forEach(function(company) {

      var total = 0;

      var invoice = Parse.Object.extend('Invoice');
      var query = new Parse.Query(invoice);
      query.equalTo('invoiceCompany', company);

      var queryPromise = query.find().then(function(invoices) {

          invoices.forEach(function(invoice) {

              total += parseFloat(invoice.get('amount'));

          });

      });

      promises.push(queryPromise);
  });

  return Parse.Promise.when(promises);

}

calculate(companies).then(function() {
  alert("Calculated Finished");
});
Sign up to request clarification or add additional context in comments.

1 Comment

THanks! it works perfectly well..just one thing. When I got 1000 companies, the above code is extremely slow. It took about 10~15 seconds to complete the transaction. How could I improve the query?

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.