Use while loop for IDB cursor iteration

Previously, I messily combined promises and callbacks because I thought we
were affected by the microtask issue:
https://github.com/gasi/idb#iteratecursor--iteratekeycursor

ESLint’s `more/no-then` encouraged me to revisit this and it works as expected.
This commit is contained in:
Daniel Gasienica 2018-03-14 12:09:48 -04:00
parent a76a6098c4
commit 5d927b73e6

View file

@ -16,24 +16,24 @@ exports.run = async (transaction) => {
await db.transaction.complete; await db.transaction.complete;
}; };
exports._initializeMessageSchemaVersion = messagesStore => // NOTE: We disable `no-await-in-loop` because we want this migration to happen
new Promise((resolve, reject) => { // in sequence and not in parallel:
messagesStore.openCursor().then(async function cursorIterate(cursor) { // https://eslint.org/docs/rules/no-await-in-loop#when-not-to-use-it
const hasMoreResults = Boolean(cursor); exports._initializeMessageSchemaVersion = async (messagesStore) => {
if (!hasMoreResults) { let cursor = await messagesStore.openCursor();
return resolve(); while (cursor) {
}
const message = cursor.value; const message = cursor.value;
console.log('Initialize schema version for message:', message.id); console.log('Initialize schema version for message:', message.id);
const messageWithInitializedSchemaVersion = Message.initializeSchemaVersion(message); const messageWithSchemaVersion = Message.initializeSchemaVersion(message);
try { try {
await messagesStore.put(messageWithInitializedSchemaVersion, message.id); // eslint-disable-next-line no-await-in-loop
await messagesStore.put(messageWithSchemaVersion, message.id);
} catch (error) { } catch (error) {
console.log('Failed to put message with initialized schema version:', message.id); console.log('Failed to put message with initialized schema version:', message.id);
} }
cursor.continue().then(cursorIterate); // eslint-disable-next-line no-await-in-loop
}).catch(reject); cursor = await cursor.continue();
}); }
};