1

Ok, i have route:

var express = require('express');
var router = express.Router();
var articles = require('../model/articles.js');

router.get('/all', function(req, res, next) {
  res.json(articles.getAll());
  console.log( "From route: " + articles.getAll());
});
module.exports = router;

and, i have model:

var mysql = require("mysql");
var con = mysql.createConnection({
    host: "localhost",
    user: "rest_news",
    password: "rest_news",
    database: "rest_news"
});
exports.getAll = function () {
    con.query('SELECT * FROM articles', function(err, rows){
        if(err) {
            return err;
        } else {
            console.log("From model:  " + rows);
            return rows;
        }
    });
};

i need get all articles from mysql, im use for that model articles, and method getAll(). What i see in console:

From route: undefined
GET /article/all 200 22.802 ms - -
From model:  [object Object],[object Object]
From model:  [object Object],[object Object]

getAll() work in second time, why?

steelRat
  • 25
  • 4
  • 2
    Does not work because you are treating asynchronous code like synchronous code. The getAll function does not return anything. – crackmigg Feb 19 '16 at 17:02

1 Answers1

0

Use a callback function :

var mysql = require("mysql");
var con = mysql.createConnection({
    host: "localhost",
    user: "rest_news",
    password: "rest_news",
    database: "rest_news"
});
exports.getAll = function (callbackFunction) {
    con.query('SELECT * FROM articles', callbackFunction);
};

And now in your route do:

var express = require('express');
var router = express.Router();
var articles = require('../model/articles.js');

router.get('/all', function(req, res, next) {
  articles.getAll(function(err, articles){
    if (err) {
        res.status(500).send({message: 'Ups something bad happened!'});
    }else{
        res.json(articles);
    }
  })
});
module.exports = router;

explanation: node uses callback to notify the main loop that something happened. In your code when you say :

  res.json(articles.getAll());

you are actually sending back undefined, that's why articles exsistt inside your query function, because that part of the code executes after the articles are fetched and res.json(articles.getAll()) executes right after you enter the model function and send the query to the sql db.

J.D.
  • 1,145
  • 2
  • 15
  • 29