承诺不一致离子

Promises not consistent Ionic

我正在使用 Ionic 4 开发一个应用程序。因此,对于这个特定的功能,我正在从 phone 中的 SQLite 数据库中获取记录并将其发布到 API。我使用 promise 来确保当前数据在循环到下一个之前已经发布,依此类推。它工作得很好,突然停止工作。

我真的不知道发生了什么,因为我的代码没有任何变化。我希望有人能帮助我。

有时,它可以工作,但只有四分之二或四分之一的数据被发送到数据库中,而其他数据则返回错误错误:未捕获(承诺):Chrome 中的 [object Object]调试器。

dataPush() {
  this.sqlite.create({
    name: 'database.db',
    location: 'default'
  }).then((db: SQLiteObject) => {
    db.executeSql('SELECT * FROM table', [])
      .then(res => {
        let promise = new Promise((resolve, reject) => {
          for (var i = 0; i < res.rows.length; i++) {
            this.array.push({
              data1: res.rows.item(i).data1,
              data2: res.rows.item(i).data2,
              data3: res.rows.item(i).data3,
              data4: res.rows.item(i).data4,
              data5: res.rows.item(i).data5,
              data6: res.rows.item(i).data6,
              sync: res.rows.item(i).sync
            })

            if (this.array[i].sync == "N") {

              this.http.post("API URL", this.array[i])
                .toPromise()
                .then(
                  res => { // Success
                    console.log(res);
                    resolve();
                  }
                );

            }
          }
        });
        return promise;
      }).catch(e => console.log('Sync Error'));
  }).catch(e => console.log(e));
}

这是给我带来问题的功能。希望有人能帮助我。提前致谢。

干杯

编辑 错误是因为它创建了一个重复的主键并且 mysql 不允许它输入 table (因此只有一个输入而其他人被拒绝)。我根据前面的键设置我的主键,并在数字上加一(全部在 PHP api 中完成)。这就是我实施承诺以确保 PHP 方在其他数据开始进入 api 之前完全完成任务(将数据插入数据库)的原因。知道为什么 promise 不起作用吗?

首先,建立你的阵列。将所有项目推入 this.array 后,您可以调用递归函数。递归函数应如下所示:

sendToApi(i) {
    this.http.post("API URL", this.array[i])
        .toPromise()
        .then(
          res => { 
            // Success
            console.log(res);
            if (i < this.array.length - 1) {
              // Call it again for the next item
              sendToApi(++i);
            }
          }
        );
}

要启动它,只需调用 sendToApi(0)。每次 .post 完成时,它会再次调用 sendToApi,但使用序列中的下一个数字