How to return auto increment id from objectstore.put() in an IndexedDB?

守給你的承諾、 提交于 2021-02-08 15:55:52

问题


How do I return the auto incremented ID after inserting a record into an IndexedDB using objectstore.put()?

Below is my code:

idb.indexedDB.addData = function (objectStore, data) {
    var db = idb.indexedDB.db;
    var trans = db.transaction([objectStore], READ_WRITE);
    var store = trans.objectStore(objectStore);
 
 
 
    var request = store.put(data);
    request.onsuccess = function (e) {
        //Success, how do I get the auto incremented id?
    };
    request.onerror = function (e) {
        console.log("Error Adding: ", e);
    };
};

回答1:


Use e.target.result. Since the API is async, you must use callback to get the return value, as follow:

idb.indexedDB.addData = function (objectStore, data, callback) {
    var db = idb.indexedDB.db;
    var trans = db.transaction([objectStore], READ_WRITE);
    var store = trans.objectStore(objectStore);
      
    var request = store.put(data);
    request.onsuccess = function (e) {
        callback(e.target.result);
    };
    request.onerror = function (e) {
        console.log("Error Adding: ", e);
        callback(undefined);
    };
};



回答2:


Solved. You can get the incremented id by using request.result.



来源:https://stackoverflow.com/questions/12502830/how-to-return-auto-increment-id-from-objectstore-put-in-an-indexeddb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!