3

I'm building up nodejs api by using async await.So my controller every function is async which receives a promise by model. For query i have used the sequelize package for interacting with the database. for using sequelize async query behaviour i choose the bluebird plugin for promisfy.

Promise.promisifyAll(sequelize)

In my model i have write a method which return data but when i call the sequelize.query it will return the data but when i write sequelize.queryAsync it should not return the data. The function is exist when i print the sequelize object. I want to know how to get the queryAsync data.

LeadModel.getActiveRecords = function () {
  return new Promise(async (resolve, reject) => {
    try {
      let output = await LeadModel.sequelize.queryAsync("SELECT * FROM some_tbl where status = '1'")
      // This below query is working fine without queryAsync
      //let output = await LeadModel.sequelize.query("SELECT * FROM some_tbl where status = '1'")
      resolve(output)
    } catch (e) {
      reject(e)
    }d
  })
}

In the controller i'm using this way.

LeadController.getlead = async function(req, res) {
    try {
        let datanew = await LeadModel.getActiveRecords();
        console.log(datanew);
    } catch (e) {
        throw e;
    }
}

Can you please help me out why the sequelize is not return async query result.

truesource
  • 397
  • 3
  • 20
  • 2
    `sequelize.query` returns a promise, no need to `promisifyAll` it. – tkausl Jun 23 '19 at 17:41
  • It requires promisifyAll because i used var Promise = require('bluebird') Promise.promisifyAll(sequelize) . It will add the async feature in all queries. – truesource Jun 24 '19 at 04:57

1 Answers1

1

What you're doing is completely unneccessary. You're returning a new promise that wraps a async function(async functions always return promises, thats how they work). And in that function you're calling sequelize query method which already returns a promise.

Also using promisifyAll on sequelize is completely unneccessary and redundant since sequelize is already async and you can use most methods with async/await.

This would do the exact same thing you're doing:

LeadModel.getActiveRecords = function() {
    return LeadModel.sequelize.query("SELECT * FROM some_tbl where status = '1'");
}

// Or you can do it in a single line
LeadModel.getActiveRecords = () => LeadModel.sequelize.query("SELECT * FROM some_tbl where status = '1'");

And to use it in the controller:

LeadController.getlead = async function(req, res, next) {
    try {
        let datanew = await LeadModel.getActiveRecords();
        console.log(datanew);
    } catch (e) {
        console.log(e);
        return next(err);
    }
}
grimurd
  • 2,750
  • 1
  • 24
  • 39
  • thanks @grimurd. Now i get it that sequelize is already returns a promise so we don't need to write extra code. – truesource Jun 25 '19 at 17:00