我正在编写一个函数,它在我的 IndexedDB 中搜索一个值,如果找到一个值,那么它应该返回 1,否则应该返回 0。问题是,尽管该值存在于数据库中,但它总是返回 0 (变量 arr 递增,但结果返回 0)。代码如下:
searchAllValues: function(store, type)
{
var arr = 0;
AAA.initDb(function()
{
var obj = {};
AAA.aaaDb.transaction(store).objectStore(store).openCursor().onsuccess = function(store)
{
var storeresult = store.target.result;
if(storeresult.value.value == type ){
arr++;
}else{console.log('value NOT found');}
storeresult ? (obj[storeresult.key] = storeresult.value.value, storeresult["continue"]()) : callback(obj)
}
});if(arr!=0){return 1}else{return 0}
}
EDIT_1: 好的,我重构了代码如下:
addInfo: function(store, type, info)
{
var arr = [];
P4S.p4sPushDb.transaction(store).objectStore(store).openCursor().onsuccess = function(store)
{
var storeresult = store.target.result;
console.log('value of storeresult==>'+storeresult.value.value);
if(storeresult.value.value == info)
{
arr.push(storeresult.value.values);return;//If it finds something it should stop here, no more search or anything to be done
}else
{
console.log('continuing..');
storeresult['continue']();
}
console.log('arr length==> '+arr.length);//If it finds nothing after the looping the whole DB, I want it to print this statement, only once (to send it to my DB actually but sending code is omitted for simplicity).
}
}
相反,我得到 console.log('arr length==>') 语句,对于我的对象存储中的每个键(实际上有 2 个)执行了 2 次。因此,当它什么也没找到并且在数据库中找到值时,它就会执行代码。有什么解决办法吗?
欢迎任何想法,谢谢
最佳答案
因为当执行 if(arr!=0){return 1}else{return 0}
行时,数据库事务尚未完成,arr 的值为 0。尽管从未使用过indexedDb,但 webSql 确实需要一些额外的毫秒来从数据库读取数据。
尝试将返回逻辑放入 onsuccess 函数中,在该函数中递增 arr。您可以通过在返回逻辑之前打印 arr 值来简单地测试它
关于JavaScript 函数总是返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36355735/