IDB:openCursor()不是函数

时间:2019-05-12 17:53:30

标签: javascript cursor indexeddb

好吧,也许我做错了什么……但是这个错误非常令人困惑。我坚持:“未捕获的TypeError:requestChatHistory.openCursor不是IDBOpenDBRequest.dbPromise.onsuccess的函数”

IDBOpenRequest可能从IDBRequest继承方法...

我试图在没有openCursor()的情况下发出请求,并从中获取第一个值。 还尝试重新创建数据库,使用其他浏览器(Chrome,Edge,Firefox)

onUpgrade承诺:

dbPromise.onupgradeneeded = function(event) { 
        let db = event.target.result;
        db.createObjectStore('keys', {keyPath: 'userId'});
        let chatHistory = db.createObjectStore('messages', { keyPath: "id", autoIncrement:true });
        chatHistory.createIndex("chatId", "chatId", { unique: false });
    };

有我要求的功能:

async function loadSavedMessages(chatId){
        let dbPromise = idb.open('clientDB', 3);
        dbPromise.onsuccess = function() {
            let db = this.result;
            let dbTransaction = db.transaction(["messages"]);
            let messages = dbTransaction.objectStore("messages");
            let index = messages.index('chatId'); 
            let requestChatHistory = index.get(chatId);
            requestChatHistory.openCursor().onsuccess = function(event) {
                let cursor = event.target.result;
                if (cursor) {
                    console.log(cursor);
                    cursor.continue();
                }
            };
        }
    }

保存数据的功能:

async function saveMessage(chatId, message, userId){
        let dbPromise = idb.open('clientDB', 3);
        dbPromise.onsuccess = function() {
            let db = this.result;
            let dbTransaction = db.transaction(["messages"], 'readwrite');
            let messages = dbTransaction.objectStore("messages");
            let mesObj = {
                chatId: chatId,
                user: userId,
                message: message,
                timestamp: Date.now()
            };
            let save = messages.add(mesObj);
            save.onerror = function(event) {
                // Handle errors!
                console.log("Something went wrong with local DB :(")
            };
            save.onsuccess = function(event) {
                // Do something with the request.result!
                console.log(`Message saved, id ${save.result}`);
            };
        }
    }

1 个答案:

答案 0 :(得分:1)

这是您的问题:

            let requestChatHistory = index.get(chatId);
            requestChatHistory.openCursor().onsuccess = function(event) {

requestChatHistoryIDBRequest,没有openCursor方法。 openCursor位于IDBIndex上,就像您的index变量一样。所以也许您打算做类似的事情:

            index.openCursor(chatId).onsuccess = function(event) {