gpt4 book ai didi

javascript - 如何从事件处理程序中返回 indexedDB 查询结果?

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

我必须从 indexedDB 返回查询结果,但结果仅在 onsuccess 事件处理程序中可用。

1  function listPeople(){
...
4 var open = indexedDB.open("AccordionDatabase",1),
5 res;
6
7 open.onsuccess = function(){
8 var db = open.result;
9 var transaction = db.transaction("PeopleStore", "readwrite");
10 var store = transaction.objectStore("PeopleStore");
11 var request = store.getAll();
12 request.onsuccess = function(event){
13 res = event.target.result;
14 console.log(res);
15 };
16
17 // Close the db when the transaction is done
18 transaction.oncomplete = function() {
19 db.close();
20 };
21
22 };
23 return res;
24 }

函数调用的输出显示 undefined,尽管控制台打印结果数组。请指导我如何使用变量作为输出。

最佳答案

您可以使用这个项目:https://github.com/jakearchibald/idb

或者您需要将 indexedDB 操作包装到一个 promise 中,从而使列表人员异步:

function listPeople() {
// ...
return new Promise(function (resolve, reject) {
var open = indexedDB.open("AccordionDatabase",1),
open.onsuccess = function() {
var db = open.result;
var transaction = db.transaction("PeopleStore", "readwrite");
var store = transaction.objectStore("PeopleStore");
var request = store.getAll();
request.onsuccess = function(event){
resolve(event.target.result);
};

request.onerror = function(event) { reject(event) }

// Close the db when the transaction is done
transaction.oncomplete = function() {
db.close();
};
transaction.onerror = function(event) { reject(event) }
};
open.onerror = function(event) { reject(event) }
})
}

// usage:
function doWorkWithListedPeople(people) {
// ...
}

function handleErrorsDuringIndexedDbRequest(event) {
// ...
}

listPeople().then(doWorkWithListedPeople).catch(handleErrorsDuringIndexedDbRequest)

// or also
listPeople().then(function(people) { doWorkWithListedPeople(people) })

问题是,您创建了一个代表最终将完成的工作的 promise 。你可以告诉 JS 最终,当 promise 被解决(成功)时,你想要 then 处理任何已经传递给 resolve 的东西。参见 https://developer.mozilla.org/cs/docs/Web/JavaScript/Reference/Global_Objects/Promisehttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function详情


编辑

此外,如果您不喜欢 thens,您可以使用 async await,它会解包 promises。请注意,您只能在异步函数中使用 await 关键字:

async function doStuff() {
try {
var people = await listPeople()
// now you can work with ppl
}
catch (err) {
// handle listPeople errors here
}
}

关于javascript - 如何从事件处理程序中返回 indexedDB 查询结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46326212/

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