Running code only after an object is updated in IndexedDB (particularly in Chrome)

前端 未结 2 1718
心在旅途
心在旅途 2020-12-21 07:58

I feel like this is a pretty mundane thing to do. I want to update an object in an IndexedDB database and then run some code after which uses the updated values.

Wha

2条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-21 08:48

    You don't need setTimeout, just wait transaction to complete as follow:

    // Update data
    var tx = db.transaction("objects", "readwrite");
    
    tx.objectStore("objects").openCursor(0).onsuccess = function (event) {
        var cursor, object;
    
        cursor = event.target.result;
        object = cursor.value;
        object.value = 43;
        cursor.update(object).onsuccess = function (event) {
            db.transaction("objects").objectStore("objects").get(0).onsuccess = function (event) {
                console.log("Cursor update onsuccess event:");
                console.log(event.target.result);
            };
        };
    
    };
    
    tx.oncomplete = function() {     
        // Read back updated data
        db.transaction("objects").objectStore("objects").get(0).onsuccess = function (event) {
            console.log("The line after the cursor update:");
            console.log(event.target.result);
       };
     }
    

    This is one of the confusing aspect of IndexedDB API. Request onsuccess don't not mean your success is written to the database. Only transaction oncomplete confirm it. The reason is, you can still abort transaction tx.abort() after write request.

提交回复
热议问题