Search code examples
javascriptnode.jses6-promise

Having trouble returning a promise and then consuming it after a database call


Im learning Javascript and im up to a section on Promises. So decided to try and convert some of my earlier projects to use Promises. But I cant get my head around it. Iv read a lot of guides and browsed through this site but I still cant understand why this isnt working.

This the function im working with, trying to do a database call that returns a promise, that can then be logged or whatever.

const getID = function (product) {
  let query = `select typeID from invTypes where UPPER(typeName) =UPPER('${product}')`;
  return new Promise((resolve, reject) => {
    resolve(
      DB.get(query, function (err, result) {
        if (err) {
          Bot.say(`Error looking up ${product}`);
        } else {
          console.log(result.typeID); //587
          return result.typeID;
        }
      })
    );
  });
};

getID(product).then((data) => console.log(data)); //Database {}

The console outputs

Database {}
587

so the .then(data => console.log(data)) //Database {} Is still happening before the promise is returned,

as you can see the other log from earlier up inside the function is actually logging after it.

Can someone help me with this iv been at this one function for hours now haha. I think I have some kind of fundamental misunderstanding that Im not picking up on from my bootcamp videos or anything im reading.


Solution

  • In promise code, you use resolve() in the asynchronous function's callback function to return values.

    const getID = function(product) {
      let query = `select typeID from invTypes where UPPER(typeName) =UPPER('${product}')`;
      return new Promise((resolve, reject) => {
        DB.get(query, function(err, result) {
          if (err) {
            Bot.say(`Error looking up ${product}`);
            reject(`Error looking up ${product}`);
          } else {
            console.log(result.typeID); //587
            resolve(result.typeID);
          }
        })
      });
    };