简体   繁体   English

等待for循环的承诺

[英]Wait for promises from a for loop

The following code does not really do what I want. 下面的代码并没有真正做到我想要的。

function doIt () {
  return new Promise (function (resolve, reject) {
    var promises = [];
    db.transaction(function(tx1){
      tx1.executeSql(function(tx2, rs) {
        for (var i = i; i < N; i++) {
          promises.push(db.transaction(function(tx3){
            ...
          }));
        }
      });
    });
    Promise.all(promises).then(resolve);
  });
}

Now it does not work, because Promise.all() gets executed, before all promises are in the array, at least I think that's correct. 现在它不起作用了,因为Promise.all()在所有的Promise都在数组中之前就已经执行了,至少我认为是正确的。

Is there a elegant way to guarantee that all these promises are finished, before doIt ends? 有没有一种优雅的方法可以保证在这些承诺结束之前完成所有这些承诺?

You can just move where the Promise.all() is located so that it's right AFTER the for loop has finished populating the array: 您可以只移动Promise.all()的位置,以便在for循环完成填充数组之后就可以了:

function doIt () {
  return new Promise (function (resolve, reject) {
    var promises = [];
    db.transaction(function(tx1){
      tx1.executeSql(function(tx2, rs) {
        for (var i = i; i < N; i++) {
          promises.push(db.transaction(function(tx3){
            ...
          }));
        }
        Promise.all(promises).then(resolve);
      });
    });

  });
}

FYI, mixing promises and callbacks can be confusing and makes consistent error handling particularly difficult. 仅供参考,混合承诺和回调可能会造成混淆,并使一致的错误处理特别困难。 Does tx1.executeSql() already return a promise? tx1.executeSql()是否已返回诺言? If so, you can do something cleaner using only promises that are already created by your database functions like this: 如果是这样,您可以仅使用数据库函数已经创建的promise来做一些更干净的事情:

function doIt() {
    return db.transaction.then(function(tx1) {
        return tx1.executeSql().then(function(tx2, rs) {
            var promises = [];
            for (var i = i; i < N; i++) {
                promises.push(db.transaction().then(function(tx3) {
                    ...
                }));
            }
            return Promise.all(promises).then(resolve);
        });
    });
}

This returns promises from .then() handlers to auto-chain promises together. 这将从.then()处理程序返回promise .then()以自动将promise链接在一起。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM