1

I'm new to node and promises. I have two files - server.js and db.js

server.js imports db.js as modules.

I'm fetching some data from a SQL database in a db.js module and I'm trying to pass that data to a function in server.js. I've successfully fetched the data from database, but when I try to pass it to the function in server.js, it only returns an undefined value.

Here's the code

server.js

const db = require('./db.js');

app.post('/api/trigger-push-msg/', function (req, res) {
  return getSubscriptionsFromDatabase()
  .then(function(subscriptions) {

    // Do something

  });
});

function getSubscriptionsFromDatabase() {
  return new Promise((resolve, reject) => {
    let subscriptions = db.getSubscriptions();

    console.log(subscriptions);  // this only prints "undefined"

    if (subscriptions != undefined) {
      resolve(subscriptions);
    } else {
      reject("No");  // this executes
    }
  })
}

db.js

module.exports = {
  getSubscriptions: function() {
    var sql = "SELECT * FROM subscriptions";

    con.query(sql, function(err, result) {
      if (err) throw err;
      console.log(result);  // this prints the same result as I want
      return result;
    })
  }
}
Anirudh Goel
  • 134
  • 3
  • 15
  • You should put the `return new Promise(…)` in the `getSubscriptions` function. You cannot `return` from that callback, you can only call `resolve`. – Bergi Jun 29 '17 at 19:32

1 Answers1

1

getSubscriptions doesn't have a return statement

and considering that there's some async content in it you should wrap all inside a promise and trigger the subsequent logic only after it resolves.

module.exports = {
  getSubscriptions: function() {
    var sql = "SELECT * FROM subscriptions";
    return new Promise(function(resolve, reject){
      con.query(sql, function(err, result) {
        if (err) return reject(err);
        resolve(result);
      })
    })
  }
}

then:

function getSubscriptionsFromDatabase() {
  return db.getSubscriptions()
  .then(function(subscriptions){
     return subscriptions;
   })
}

and in your route:

app.post('/api/trigger-push-msg/', function (req, res) {
 getSubscriptionsFromDatabase()
  .then(function(subscriptions) {
    res.send(subscriptions);
  })
  .catch(function(err){
    res.sendStatus(500);
  })
});
Karim
  • 8,454
  • 3
  • 25
  • 33