IndexedDB 成功与不需要的比赛
IndexedDB success vs ungradeneeded race
我用新版本号打开 indexedDB
var R = indexedDB.open("myDB", 2); // <- new version
R.onupgradeneeded = longRunningFunction;
R.onsuccess = longRunningFunction2;
现在我需要在两个 运行ning 长函数完成后 运行 一个函数。哪种代码模式适用于此?
使用承诺或回调。等待成功事件触发,完成它的工作,然后解决承诺或调用回调。然后你可以在承诺解决后或回调被调用时做一些事情。
编辑,这是一个粗略的例子:
function myOpenIndexedDB(name, version, onupgradeneeded) {
return new Promise((resolve, reject) => {
var request = indexedDB.open(name, version);
request.onupgradeneeded = onupgradeneeded;
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
}
function myOnUpgradeNeeded(event) {
console.log('Performing database upgrade');
const openRequest = event.target;
// just to demonstrate
const versionChangeTransaction = openRequest.transaction;
versionChangeTransaction.oncomplete = () => {
console.log('The version change transaction completed ' +
'which basically means the upgradeneeded handler completed');
};
}
async function main() {
console.log('Connecting to database');
const indexedDbConn = await myOpenIndexedDB('myDb', 2, myOnUpgradeNeeded);
console.log('Connected to database', indexedDbConn.name);
// Do more stuff
await runSomeQuery(indexedDbConn);
}
// Run the example
main().catch(console.error);
引用次数
有关详细信息,请参阅
中突出显示的浅绿色块
我用新版本号打开 indexedDB
var R = indexedDB.open("myDB", 2); // <- new version
R.onupgradeneeded = longRunningFunction;
R.onsuccess = longRunningFunction2;
现在我需要在两个 运行ning 长函数完成后 运行 一个函数。哪种代码模式适用于此?
使用承诺或回调。等待成功事件触发,完成它的工作,然后解决承诺或调用回调。然后你可以在承诺解决后或回调被调用时做一些事情。
编辑,这是一个粗略的例子:
function myOpenIndexedDB(name, version, onupgradeneeded) {
return new Promise((resolve, reject) => {
var request = indexedDB.open(name, version);
request.onupgradeneeded = onupgradeneeded;
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
}
function myOnUpgradeNeeded(event) {
console.log('Performing database upgrade');
const openRequest = event.target;
// just to demonstrate
const versionChangeTransaction = openRequest.transaction;
versionChangeTransaction.oncomplete = () => {
console.log('The version change transaction completed ' +
'which basically means the upgradeneeded handler completed');
};
}
async function main() {
console.log('Connecting to database');
const indexedDbConn = await myOpenIndexedDB('myDb', 2, myOnUpgradeNeeded);
console.log('Connected to database', indexedDbConn.name);
// Do more stuff
await runSomeQuery(indexedDbConn);
}
// Run the example
main().catch(console.error);
引用次数
有关详细信息,请参阅
中突出显示的浅绿色块