From 5d927b73e602cf5d05772c74093462ee9c0aa0b8 Mon Sep 17 00:00:00 2001 From: Daniel Gasienica Date: Wed, 14 Mar 2018 12:09:48 -0400 Subject: [PATCH] Use `while` loop for IDB cursor iteration MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- js/modules/migrations/17/index.js | 42 +++++++++++++++---------------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/js/modules/migrations/17/index.js b/js/modules/migrations/17/index.js index 618c95156..5a8472ec3 100644 --- a/js/modules/migrations/17/index.js +++ b/js/modules/migrations/17/index.js @@ -16,24 +16,24 @@ exports.run = async (transaction) => { await db.transaction.complete; }; -exports._initializeMessageSchemaVersion = messagesStore => - new Promise((resolve, reject) => { - messagesStore.openCursor().then(async function cursorIterate(cursor) { - const hasMoreResults = Boolean(cursor); - if (!hasMoreResults) { - return resolve(); - } - - const message = cursor.value; - console.log('Initialize schema version for message:', message.id); - - const messageWithInitializedSchemaVersion = Message.initializeSchemaVersion(message); - try { - await messagesStore.put(messageWithInitializedSchemaVersion, message.id); - } catch (error) { - console.log('Failed to put message with initialized schema version:', message.id); - } - - cursor.continue().then(cursorIterate); - }).catch(reject); - }); +// NOTE: We disable `no-await-in-loop` because we want this migration to happen +// in sequence and not in parallel: +// https://eslint.org/docs/rules/no-await-in-loop#when-not-to-use-it +exports._initializeMessageSchemaVersion = async (messagesStore) => { + let cursor = await messagesStore.openCursor(); + while (cursor) { + const message = cursor.value; + console.log('Initialize schema version for message:', message.id); + + const messageWithSchemaVersion = Message.initializeSchemaVersion(message); + try { + // eslint-disable-next-line no-await-in-loop + await messagesStore.put(messageWithSchemaVersion, message.id); + } catch (error) { + console.log('Failed to put message with initialized schema version:', message.id); + } + + // eslint-disable-next-line no-await-in-loop + cursor = await cursor.continue(); + } +};