首先,我找不到適合此問題的標題 - 請隨時編輯。IndexDB光標.onsucess作爲承諾
我有以下的功能,從INDEXDB讀取對象,
loadNeededParcels = property => {
const dbResults = [];
var readTransaction = this.db
.transaction("parcelData")
.objectStore("parcelData");
readTransaction.openCursor().onerror = e => {
console.log("open cursor error ", e);
};
readTransaction.openCursor().onsuccess = e => {
const cursor = e.target.result;
if (cursor) {
dbResults.push(cursor.value);
cursor.continue();
} else {
return dbResults;
}
};
};
現在,當我把一個簡單的函數調用這個函數,例如:
console.log(loadNeededParcels('hasData'))
控制檯日誌undefined
。我猜這是因爲函數不等待光標完成並返回dbResults
變量?
所以我的問題是這樣的 - 我該如何重寫這個函數作爲承諾,或者寧可等待readTransaction.openCursor().onsucess
觸發?
所以預期的結果是函數實際返回退出前從數據庫中讀取的值。
由於.getAll()
該方法在IE中不受支持,因此我使用了遊標。
在這裏,您將屬性作爲參數傳遞給openCursor - 但由於屬性不是關鍵,所以這不起作用。財產之後的問號代表什麼?但是,使用你的方法重新編寫了這個方法,只用了一次openCursor,它比以前快了一點 –
它是僞代碼。我不明白你的代碼試圖做什麼。問號應該表明這一點。不帶範圍或值參數打開遊標意味着您正在遍歷存儲中的所有對象。 – Josh
ah基本上從數據庫中檢索所有記錄,然後只返回沒有傳遞屬性的記錄爲undefined(即,如果parcel [property] === undefined) –