0

Here's some code to join something from 3 object stores:

let db;
indexedDB.open('db', 1).onsuccess = ev => {
    db = ev.target.result;

    const tran = db.transaction(['s1', 's2', 's3']);
    tran.objectStore('s1').get('third').onsuccess = ev1 =>
        tran.objectStore('s2').index('connectTo').get('third').onsuccess = ev2 =>
            tran.objectStore('s3').index('connectTo').get('third').onsuccess = ev3 => {
                const [res1, res2, res3] = [ev1.target.result, ev2.target.result, ev3.target.result];
                const result = {...res1, ...res2, ...res3};
                ......
            }
}

Can I use promises or other means like async/await to avoid the heavy nesting? It'd be good if I can put these query processes in a function and get the result object as the return value.

Josh
  • 17,834
  • 7
  • 50
  • 68
kuoln
  • 1
  • 1
    If you want to use promises, you might have to consider using a library like [this](https://github.com/jakearchibald/idb) – TKoL Nov 27 '20 at 16:18
  • Does this answer your question? [How do I convert an existing callback API to promises?](https://stackoverflow.com/questions/22519784/how-do-i-convert-an-existing-callback-api-to-promises) – Liam Nov 27 '20 at 16:22

1 Answers1

0

Something like this should work.

const someFunction = async () => {
  let db
  const openDB = await indexedDB.open('db', 1)
  db = openDB.target.result
  const tran = db.transaction(['s1', 's2', 's3'])
  const ev1 = await tran.objectStore('s1').get('third')
  const ev2 = await tran.objectStore('s2').index('connectTo').get('third')
  const ev3 = await tran.objectStore('s3').index('connectTo').get('third')
  const [res1, res2, res3] = [
    ev1.target.result,
    ev2.target.result,
    ev3.target.result,
  ]
  const result = { ...res1, ...res2, ...res3 }
}
someFunction()

Personally I would store the results like this and eliminate the need for copies (if possible for you).

const result = { ...ev1.target.result, ...ev2.target.result, ...ev3.target.result }
omeanwell
  • 1,847
  • 1
  • 10
  • 16
  • Cannot read property 'result' of undefined. I can only get the result by ev1.onsuccess = ev => console.log(ev.target.result) and do the same on ev2 and ev3. So I can't merge the results to a single object. – kuoln Nov 27 '20 at 17:31
  • But you should be able to if you use my method above – omeanwell Nov 27 '20 at 17:32
  • No, ev1.target, ev2.target, ev3.target are all undefined. – kuoln Nov 27 '20 at 17:41