Indexeddb游标等待响应?

时间:2019-02-09 11:12:37

标签: javascript angular ionic3 indexeddb

我有一个包含indexeddb数据库的应用程序。它会保存信息一段时间。如果此信息未传递到服务器(例如由于网络错误),则“已同步”设置为false。现在,我想创建一个函数,该函数能够将状态为“ synced:false”的项目上载到服务器。

想法是遍历db,每次有一个带有false的条目时,将其上载到服务器,并成功更新本地(indexeddb)db中的值。

我遇到的问题是我看不到如何让游标操作等待服务器(REST API)的响应,然后相应地执行操作(更新本地值“ synced:false”-> “ synced:true”。服务器更新正常。

以下是可正常工作的Stackblitz,可在首页上显示完整代码:

https://stackblitz.com/edit/ionic-thu3eg

输出在控制台中。 这是一个实际问题的例子。

  update() {
    var callstring: string;
    let nowTime = new Date().toISOString();
    let nowTimes = dateFns.format(nowTime, 'YYYY-MM-DD HH:mm:ss');
    var headers = new Headers();
    headers.append("Accept", "application/json");
    headers.append("Content-Type", "application/json");
    let options = new RequestOptions({ headers: headers });

    const dbPromise = openDb('testdb', 1);
    dbPromise.then(async db => {
      const tx = db.transaction('scans', 'readwrite');
      tx.objectStore('scans').iterateCursor(async cursor => {
        if (!cursor) return;
        if (cursor.value.synced == 'false') {
          console.log(cursor.value);

          await new Promise((resolve, reject) => {
            this.http.get('https://jsonplaceholder.typicode.com/posts/1')
              .map(res => res.json())
              .subscribe(res => {
                console.log('response : ', res.id);
                resolve(res)
                return callstring = res.id;
              }, error => {
                reject(error)
              });
          });

          if (callstring == '1') {
            console.log('do something : ', callstring);
            cursor.value.synced = 'true';
            cursor.value.time = nowTimes;
            cursor.update(cursor.value);
          } else {
            console.log('sorry too late');
          }
        }
        await cursor.continue();
      });
      await tx.complete.then(() => console.log('done cursoring'));

    }).then(() => {
      this.toastCtrl.create({
        message: "DB updated",
        duration: 2000,
        position: 'top',
        cssClass: "toast-mess"
      }).present();
    });
  }    

因此,如果callstring = 1,则应将indexeddb中的“ false”值更新为“ true”。

我该如何解决? 谢谢

0 个答案:

没有答案
相关问题