Search code examples
javascriptpromisedexie

Getting a value from Dexie promise


Trying to get data returned by the below function using Dexie.JS:

function findEvent(key) {
  let snippet = '';
  if (!db.isOpen()) {
    lastEvent = lastEvent.then(() => db.open());
  }
  lastEvent = lastEvent.then(() => db.transaction('r', db.events, () => {
    db.events.each((element) => {
      let d = element.cause.data;
      if (d.hasOwnProperty('deleted') && (false == d.deleted) && d.hasOwnProperty('abbreviation') && 
        d.hasOwnProperty('contents') && (d.abbreviation == key)) {
          console.log(`found matching snippet for key: ${key}, contents: ${d.contents}`);
          snippet = d.contents;
      }
    }).then(() => {
      console.log('search callback returning:', snippet);
      return snippet;
    });
  }));

  return lastEvent;
}

I call it as:

  return findEvent(request.key).then((result) => {
    console.log(`findEvent return: ${result}`);
  });

Apparently, I am doing something wrong. My promises are executed in the correct order. I get snippet printed correctly in the log from inside findEvent. When result is logged in the calling code, it is undefined.

What should be done differently?


Solution

  • You're not returning the promise from db.events.each, so undefined gets piped into your top level promise.