Parse.com Javascript Asyn Call in Loop

时间:2015-06-23 14:43:11

标签: javascript asynchronous parse-platform foreach promise

我有一份公司名单,想要计算发给每家公司的发票总额。以下是我写的代码。 (实际逻辑在循环中更复杂,但在这里将它们取出)

基本上我想在循环中的业务逻辑完成后提醒消息 (同样,这里会做更复杂的事情)。我觉得我可以使用 Promises 来解决这个问题,但我不太清楚如何使用它。我没有完全按照Parse.com的文件。我已经坚持了几个小时。请帮忙!

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 个答案:

答案 0 :(得分:2)

你可以在并列中使用promises:

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

这将是这样的:

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