0

I have this function but I am unable to put it inside my item variable. How do I put it outside the item variable?

function getItems(id) {
    let item;

    sequelize.query("SELECT * FROM table WHERE id = " + id, {type: Sequelize.QueryTypes.SELECT})
    .then(myTableRows => {
        // item = JSON.stringify(myTableRows);
    });

    return item;
}
Daniel
  • 205
  • 2
  • 12

1 Answers1

0

Your sequelize query returns a promise, and you cannot set the value of the item inside the promise and expect an immediate response. If you want it to work this way, you need to handle the promise correctly, or use an async-await. You can reconfigure your function to look like this, which will handle the issue:

async function getItems(id) {
   let item;

   item = await sequelize.query("SELECT * FROM table WHERE id = " + id, {type: Sequelize.QueryTypes.SELECT});

   return item;
}

===========================================================================

Update:

I am not sure your experience level with node, but many aspects of node leverage promises. At a high level, what that means is perform some action, then do something once its done. With sequelize, you are performing a SQL query, and once you get a response, you can now do something with this data.

Async-Await is a way to make promises a bit more straightforward in understanding, but act the same. There are plenty of articles online to help you better understand the concepts.

Now the function that is calling getItems needs to also be an async-await, or call it as a promise in order to actually get the values. For example:

async function test(id) {
  let items = await getItems(id);
  console.log(items)

}

Hopefully that clears up some confusion, though you many need to learn a bit more about promises if you are unclear about how they work. Hopefully this helps.

CoolestNerdIII
  • 770
  • 4
  • 10
  • I am quite confused. Now it's returning like this: Promise { } } I have tried reading something about that but I can't understand most of it. What is the purpose of having async and await instead of the usual function and how do I convert the Promise to the equivalent data? – Daniel Dec 03 '18 at 18:55
  • I am not sure if I can adequately answer in the comments, so I will just updated my answer. – CoolestNerdIII Dec 03 '18 at 18:59