gpt4 book ai didi

html - 如何同步循环遍历 indexedDB 表?

转载 作者:搜寻专家 更新时间:2023-10-31 23:09:20 27 4
gpt4 key购买 nike

我想在 JS 中编写一个函数,我将循环遍历索引数据库中的表并获取表最后修改的最大值并返回该值

function readData(){
var trans = '';
trans = idb.transaction(["tableName"],'readonly'); // Create the transaction
var request = trans.objectStore("tableName").openCursor();
request.onsuccess = function(e) {
var cursor = request.result || e.result;
if(cursor) {
// logic to and find maximum
} else {
return // max last modified
}
cursor.continue();
}
}

IMP——既然 onsuccess 方法是异步的,我怎样才能让它同步呢?这样我的方法 readData() 将仅在成功找到最大最后修改记录时返回。如果需要,我可以同步调用此方法 (readData()) 以获取 2-3 个表的最后修改记录。

最佳答案

同步 API 仅在网络 worker 中可用。所以这将是第一个要求。 (据我所知目前只有IE10支持)

您可以提供的另一个镜头是使用 JS 1.7 并使用 yield 关键字。有关它的更多信息,请查看 here

我建议使用您在达到最新值时调用的 callbakck 方法。

function readData(callback){     
var trans = '';
trans = idb.transaction(["tableName"],'readonly'); //Create the transaction
var request = trans.objectStore("tableName").openCursor();
var maxKey;
request.onsuccess = function(e) {
var cursor = request.result || e.result;
if(cursor.value){
//logic to and find maximum
maxKey = cursor.primaryKey
cursor.continue();
}
}
trans.oncomplete = function(e) {
callback(maxKey);
}
}

关于html - 如何同步循环遍历 indexedDB 表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12092083/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com