等待for循环的承诺 [英] Wait for promises from a for loop

查看:83
本文介绍了等待for循环的承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码并没有真正做到我想要的.

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

现在它不起作用了,因为Promise.all()被执行了,在所有promise都在数组中之前,至少我认为这是正确的.

Now it does not work, because Promise.all() gets executed, before all promises are in the array, at least I think that's correct.

是否有一种优雅的方法可以保证在兑现结束之前完成所有这些承诺?

Is there a elegant way to guarantee that all these promises are finished, before doIt ends?

推荐答案

您可以移动Promise.all()所在的位置,以便在for循环完成填充数组之后就可以将其正确:

You can just move where the Promise.all() is located so that it's right AFTER the for loop has finished populating the array:

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

  });
}

仅供参考,混淆承诺和回调可能会造成混淆,并使一致的错误处理特别困难. tx1.executeSql()已经返回承诺了吗?如果是这样,您可以仅使用数据库功能已经创建的promise来做一些更清洁的事情:

FYI, mixing promises and callbacks can be confusing and makes consistent error handling particularly difficult. Does tx1.executeSql() already return a promise? If so, you can do something cleaner using only promises that are already created by your database functions like this:

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

这将返回来自.then()处理程序的诺言,以将诺言自动链接在一起.

This returns promises from .then() handlers to auto-chain promises together.

这篇关于等待for循环的承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆