Search code examples
node.jsexpressendpoint

Node JS Sequalize Get All


I have this:

//file index.js
.
.
.

// Routes
app.get("/chat", async (req, res, next) => {  
  const list = await getAll();
  console.log("list: ", list);
  res.json(list);
});
 
.
.
.
const getAll = () => {
  sequelize.sync().then(() => {
    Chat.findAll().then(res => { 
        //console.log("resp: ", res);
        return  res;
      }).catch((error) => {
          console.error('Failed to retrieve data : ', error);
      });

    }).catch((error) => {
        console.error('Unable to create table : ', error);
    });
}

I just want get data of table chat, so I'm creating a simple endpoint to get it, so I check on console.log("resp: ", res); in getAll() and I saw the data of table chat on console, but I tested the endpoint localhost:3001/chat and I don't get it, so I tested console.log("list: ", list); on app.get("/chat", async (req, res, next) and I got undefined

what's wrong??


Solution

  • Try using async function for the callback function as well.

        //file index.js
        .
        .
        .
        
        // Routes
        app.get("/chat", async (req, res, next) => {  
          const list = await getAll();
          console.log("list: ", list);
          res.send(list);
        });
         
        .
        .
        .
        const getAll = async () => {
          await sequelize.sync();
          const res = await Chat.findAll();
                return  res;
       }