簡體   English   中英

Dexie JS 嵌套集合無法在 Promise 鏈中解析

[英]Dexie JS Nested Collections Not Resolving in Promise Chain

我一直在使用 Dexie JS 來管理 IndexDB 數據存儲,現在想要將數據存儲與遠程數據庫同步。 我遇到的問題是我想將所有關系/子記錄嵌套在集合中各自的父記錄下,然后使用一些 AJAX 將整個組/列表發送到遠程服務器。

在實踐中,我看到的是子記錄在被推送到遠程服務器時不存在。 但是,我確實在 console.log() 中看到了它們。 我知道這是因為 console.log() 獲取實際數據的時間比遠程推送數據的時間要晚得多。 我也知道這是承諾鏈的一個常見問題,但不知何故無法解決它。

這是我到目前為止所擁有的。

function PushRemote(items, modelName) {

    console.log(items);

$.ajax({
   type: 'POST',
   url: '/' + modelName + '/AsyncSave',
   contentType: 'application/json; charset=utf-8',
   dataType: 'json',
   data: JSON.stringify(DataTransferItemList),
   success: function (response) {
       iDB.open().then(function () {
               return iDB.table(modelName).update(response, { isNotSynced: "false" });
       });
   },
   error: function (response) {
       console.error(response);
   }
});
}

function PushTableToRemote(modelName) {
  iDB.transaction('rw',
    iDB.Comments,
    iDB.CommentRatings,
    iDB.Posts,
    iDB.PostRatings,
    iDB.Reviews,
    () => {
        iDB.table(modelName).where({ isNotSynced: "true" }).toArray(items => {

            items.forEach(item => {

                if (modelName == 'Comments') {
                    iDB.CommentRatings.where({ CommentId: item.CommentId }).toArray(c => item.CommentRatings = c);
                }

                if (modelName == 'Posts') {
                    iDB.PostRatings.where({ PostId: item.PostId }).toArray(p => item.PostRatings = p);
                }

            })

            return items;
        })
        .then(items => {
            if (items && items.length > 0) {
                PushRemote(item, modelName);
            }
        });
    });
}

pushTableToRemote('Comments');

好吧,如果你不能通過承諾鏈,那么你就繞過承諾鏈。 ;)

最終使用生成器函數而不是承諾鏈( https://dexie.org/docs/Simplify-with-yield.html )實現spawn()yield 至少對我來說,這更直接。 並且像魅力一樣工作。 你的旅費可能會改變。

function PushTableToRemote(modelName) {

spawn(function* () {

    var items = yield iDB.table(modelName).where({ isNotSynced: "true" }).toArray();

    if (items && items.length > 0) {

        if (modelName == 'Comments') {
            for (var i = 0; i < items.length; i++) {
                var CommentRatings = yield iDB.CommentRatings.where({ CommentId: items[i].CommentId }).toArray();
                items[i].CommentRatings = CommentRatings;
            }
        }

        if (modelName == 'Posts') {
            for (var i = 0; i < items.length; i++) {
                var PostRatings = yield iDB.PostRatings.where({ PostId: items[i].PostId }).toArray();
                items[i].PostRatings = PostRatings;
            }
        }

        PushRemote(items, modelName);
    }
});
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM