Promise中使用了for循环后,不能获取到最终结果,如果改为promise.all该如何修改

发布于 2022-09-07 19:58:04 字数 4905 浏览 9 评论 0

如下代码,我其中使用了多次读取数据库,并且获取到的数据在进行循环,循环后在进行数据库查询,最终resolve后,我得到的结果仅仅只是一小部分数据,还剩余一部分数据并未resolve,但是通过console.log可以打印出所有数据,resolv执行的时候,其实for循环还未执行完

getProducts(params) {
  return new Promise((resolve, reject) => {
    if (params) {
      this.getDb().then((db: SQLiteObject) => {
        db.transaction((run) => {
          var sql = 'SELECT * FROM product_content';
          run.executeSql(sql, [],
            (run, res) => {
              if (res.rows.length != 0) {
                let result = {
                   product_ids: {}
                };
                let retTmp = []
                let exTmp = [1,2,100,600,500,800,900,700,701,300]
                let categoryIds = []
                for (var i = 0; i < res.rows.length; i++) {
                  var product = res.rows.item(i);
                  categoryIds.push(product.categoryIds)
                  for (var k = 0; k < categoryIds.length; k++) {
                    var _cid = categoryIds[k]
                    sql = 'select id FROM product where category like "%,' + _cid + ',%"';
                    run.executeSql(sql, [],
                      (run, res_id) => {
                        if (res_id.rows.length != 0) {
                          for (var i = 0; i < res_id.rows.length; i++) {
                            var productId = res_id.rows.item(i).ID
                            retTmp.push(productId)
                          }
                        }
                      })
                  }
                }
                // setTimeout(() => {
                  let newRetTmp = Array.from(new Set(retTmp))
                  let newExTmp = Array.from(new Set())

                  if (newExTmp.length > 0) {
                    newRetTmp.map((rettmp, index) => {
                      exTmp.map(extmp => {
                        if (rettmp != extmp) {
                          result.product_ids[newRet] = true
                        }
                      })
                    })
                  }

                  resolve(result);
                // }, 500)
              } else {
                let result = {
                  data: {
                    product_ids: {}
                  }
                };
                resolve(result);
              }
            })
        })
      })
    }
  })
}

之前在网上看到使用Promise.all()的方法,我将其修改成如下代码,代码看上去没有什么问题,但是一到Promise.all的地方就一直没有resolve了:

getProducts(params) {
  return new Promise((resolve, reject) => {
    if (params) {
      this.getDb().then((db: SQLiteObject) => {
        db.transaction((run) => {
          var sql = 'SELECT * FROM product_content';
          run.executeSql(sql, [],
            (run, res) => {
              if (res.rows.length != 0) {
                let result = {
                    product_ids: {}
                };
                let retTmp = []
                let exTmp = [1,2,100,600,500,800,900,700,701,300]
                let categoryIds = []
                let promise = []
                for (var i = 0; i < res.rows.length; i++) {
promise.push(new Promise((resolve,reject)=>{
                  var product = res.rows.item(i);
                  categoryIds.push(product.categoryIds)
                  for (var k = 0; k < categoryIds.length; k++) {
                    var _cid = categoryIds[k]
                    sql = 'select id FROM product where category like "%,' + _cid + ',%"';
                    run.executeSql(sql, [],
                      (run, res_id) => {
                        if (res_id.rows.length != 0) {
                          for (var i = 0; i < res_id.rows.length; i++) {
                            var productId = res_id.rows.item(i).ID
                            retTmp.push(productId)
                            // this.helperService.console('c0', productId)
                          }
                        }
                      })
                  }
}))
                }
Promise.all(promise).then(res => {
              // setTimeout(() => {
                let ATmp = Array.from(new Set(retTmp))

                if (newExTmp.length > 0) {
                  exTmp.map((rettmp, index) => {
                    newExTmp.map(extmp => {
                      if (rettmp != extmp) {
                        result.product_ids[newRet] = true
                      }
                    })
                  })
                }
                resolve(result);
              // }, 500)
})
                
              } else {
                let result = {
                  data: {
                    product_ids: {}
                  }
                };
                resolve(result);
              }
            })
        })
      })
    }
  })
}

根据以上代码,都无法得到想要的结果,第二种方法更是一直处于pendding状态,真不知道该如何进行解决,望各位大神支招

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

自我难过 2022-09-14 19:58:04
  1. db的查询为异步,promise的resolve请在异步的回调函数中使用。
  2. 你第二个例子一直pending是因为你没有在那个循环查询db时使用resolve,没有resolve或reject或异常,promise一直等待。

所以,每一次db查询都应被包裹在一个promise中,然后外面使用promise.all. 第二个例子,明显你还少用了一个promise.All:
下面这段代码处,也需要创建一个promise数组,循环结束后,执行promise.all(promise数组),then 将结果使用最外侧的resolve返回。

sql = 'select id FROM product where category like "%,' + _cid + ',%"';
run.executeSql(sql, [], ...

改造后,大概代码时这个样子的(并未执行过,只是示范):

getProducts(params) {
    return new Promise((resolve, reject) =>{
        if (params) {
            this.getDb().then((db: SQLiteObject) =>{
                db.transaction((run) =>{
                    var sql = 'SELECT * FROM product_content';
                    run.executeSql(sql, [], (run, res) =>{
                        if (res.rows.length != 0) {
                            let result = {
                                product_ids: {}
                            };
                            let retTmp = [];
                            let exTmp = [1, 2, 100, 600, 500, 800, 900, 700, 701, 300]; 
                            let categoryIds = [];
                            let promise = [];
                            for (var i = 0; i < res.rows.length; i++) {
                                promise.push(new Promise((resolve1, reject1) =>{
                                    var product = res.rows.item(i);
                                    categoryIds.push(product.categoryIds);
                                    var innerPromise = [];
                                    for (var k = 0; k < categoryIds.length; k++) {
                                      innerPromise.push(new Promise((resolve2, reject2) => {
                                        var _cid = categoryIds[k];

                                        sql = 'select id FROM product where category like "%,' + _cid + ',%"';
                                        run.executeSql(sql, [], (run, res_id) =>{
                                            if (res_id.rows.length != 0) {
                                                var productids = [];
                                                for (var i = 0; i < res_id.rows.length; i++) {
                                                    var productId = res_id.rows.item(i).ID retTmp.push(productId)
                                                    // this.helperService.console('c0', productId)
                                                    productids.push(productId);
                                                }
                                                resolve2(productids);
                                            } else {
                                                resolve2([]);
                                            }
                                        });
                                      }));
                                    }
                                    Promise.all(innerPromise).then(productIdsArray=>resolve1(productIdsArray));
                                }))
                            }
                            Promise.all(promise).then(res =>{
                                // setTimeout(() => {
                                let ATmp = Array.from(new Set(retTmp))

                                if (newExTmp.length > 0) {
                                    exTmp.map((rettmp, index) =>{
                                        newExTmp.map(extmp =>{
                                            if (rettmp != extmp) {
                                                result.product_ids[newRet] = true
                                            }
                                        })
                                    })
                                }
                                resolve(result);
                                // }, 500)
                            })

                        } else {
                            let result = {
                                data: {
                                    product_ids: {}
                                }
                            };
                            resolve(result);
                        }
                    })
                })
            })
        }
    })
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文