gpt4 book ai didi

javascript - var result = wait someFunc() 返回一个对象,但我期望对象列表

转载 作者:行者123 更新时间:2023-12-02 22:47:25 25 4
gpt4 key购买 nike

我编写了以下函数来加载indexeddb。 (来自IndexedDB 備忘メモ)我认为这个函数应该返回对象数组。但是,有时它会返回一个对象。 bug的可能性有哪些?Chrome 开发者工具在“加载”函数中表示对象类型为数组。但是,收到“记录”后是对象类型。

    async function load(dbobj, db, index, range) {
return new Promise(async (resolve, reject) => {
const saves = [];
const req = db.transaction(dbobj.storeName).objectStore(dbobj.storeName).index(index).openCursor(range);
const onfinished = () => {
console.log(`${saves.length} saves found.`);
if (saves.length > 0) {
resolve(saves[saves.length - 1]);
}
};
req.onerror = reject;
req.onsuccess = (ev) => {
const cur = ev.target.result;
if (cur) {
saves.push(cur.value);
cur.continue();
} else {
onfinished();
}
};
});
}

// example of receiving data
var records = await load(dbobj, db, index, range);

最佳答案

您仅解析最后一个索引处的值!如果需要整个数组,则解析(保存);

async function load(dbobj, db, index, range) {
return new Promise(async (resolve, reject) => {
const saves = [];
const req = db.transaction(dbobj.storeName).objectStore(dbobj.storeName).index(index).openCursor(range);
const onfinished = () => {
console.log(`${saves.length} saves found.`);
if (saves.length > 0) {
resolve(saves); // you are resolving only the value at the last index! resolve(saves) if you need the entire array;
}
};
req.onerror = reject;
req.onsuccess = (ev) => {
const cur = ev.target.result;
if (cur) {
saves.push(cur.value);
cur.continue();
} else {
onfinished();
}
};
});
}

关于javascript - var result = wait someFunc() 返回一个对象,但我期望对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58335984/

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