我試圖從索引數據庫中獲取某個鍵的值,並將它們添加到數組中,該數組在onsuccess函數內工作正常,但在其之後爲空。我通過命令猜測記錄到控制檯的兩年[0]顯示該問題與異步有關。我顯然不是真正理解事情發生的順序以及如何實現我想要的。有人可以幫助我理解問題是什麼,也可能指向正確的方向來克服它。數組填充IndexedDB對象存儲鍵的值是否全局無法訪問?
// the array I want the values in
var years = new Array();
// function retrieves all objects between certain years, low and high
function getYears(low, high){
var request = window.indexedDB.open("matchDB", 1);
request.onerror = function(event) {console.log("onerror");}
request.onsuccess = function(event) {
var db = event.target.result;
var objectStore = db.transaction(["matches"], 'readonly').objectStore("matches");
var index = objectStore.index("year");
var range = IDBKeyRange.bound(low, high, true, true);
var request = index.openCursor(range);
request.onsuccess = function(evt) {
var cursor = evt.target.result;
if (cursor) {
var matchList = cursor.value;
// the value of the key year is pushed into the array years
years.push(matchList.year);
console.log(years[0]); // this works
cursor.continue();
}
}
console.log(years[0]); //this is undefined
}
}
數據庫訪問是異步的。任何依賴於結果的事情都必須在'onsuccess'函數中完成。 – Barmar
這就像AJAX,所以請參閱:http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call – Barmar