A
A
amstr1k2015-03-21 21:11:53
Node.js
amstr1k, 2015-03-21 21:11:53

How to implement sending 2 or more variables in SailsJs?

There is an application in which there is a pagination. The template is given the first 5 elements and the total number of all elements (for example, 100).
How to implement return to the template of these elements?

index: function (req, res) {
    Post.find()
    .sort('id DESC')
      .paginate({page: req.param('page', 0), limit: 5})
      .exec(function (err, posts) {
        if (err) return res.send(500);
        res.view({
          posts: posts,
          countItems: //тут 100
        });
      });
  },

Tried like this but throws an error
index: function (req, res) {
    Post.count(function (err, num) {
        if(err) {
           return console.log(err);
        }
    })

    Post.find()
      .sort('id DESC')
      .paginate({page: req.param('page', 0), limit: 5})
      .exec(function (err, posts) {
        if (err) return res.send(500);
        res.view({
          posts: posts,
countItems: num
        });
      });
  },

Answer the question

In order to leave comments, you need to log in

3 answer(s)
F
friktor, 2015-03-22
@amstr1k

Umm... Here you should use promises, i.e. it should be something like.

index: function (req, res, next) {
    var Promise = require("bluebird");
    
    var countAllPosts = Post.count()
      .then(function countResult (count) {
        // Сторонние действия, итерации, и т.д...
        return count; // Обязательно - так мы возвращаем объект promise
      }); 

    var posts = Post.find()
      .sort({
        "id": "desc"
      })
      
      .paginate({
        page: req.param("page", 1),
        limit: 5
      })

      .then(function (posts) {
        return posts; // также возвращаем promise объект
      });

    Promise
      // Метод объеденения нескольких промисов.
      .join(countAllPosts, posts, function (count, posts) {
        res.view({
          countPosts: countPosts,
          posts: posts
        });
      })

      // Независимая обработка ошибок, вне основной логики: cb(err, data) не лучший способ работы с данными в nodejs. 
      .catch(function (errors) {
        res.serverError(); // res.send(500) не родной метод sails и его лучше не использовать, имхо
      })


  }

The main juice here is promises, from the bluebird library , and the key factor is returning an object with a promise. After that - having created several variables with actions on this technology - we combine them using join - and the library asynchronously executing them creates a function with the results of the selection.
After that, we give the data - completed without errors. We handle errors themselves independently of the general logic. That's it. Personally, I advise you to study Bluebird in more detail - in Sails everything works on it.
About your personal mistakes - you made 2 different areas of action. The callback does not inline the variable into the main scope - it executes asynchronously within the function itself - and therefore is not visible to any other functions. And the runtime error is an unknown variable. If you wanted the num variable to be visible from the callback, you had to call the post search function inside the callback.
PS - read all sails documentation. Use tracing and error logging more, at least through sails.log.error.

S
smanioso, 2015-03-22
@smanioso

Instead of num use posts.length

A
amstr1k, 2015-03-22
@amstr1k

smanioso

index: function (req, res) {
    // Поиск в модели Post
    Post.find()
      .sort('id DESC')
      .paginate({page: req.param('page', 1), limit: 1})
      .exec(function (err, posts) {
        // Если ошибка вывести страницу 500 (с логом)
        if (err) return res.send(500);
        res.view({
          posts: posts,
          currentPage: req.param('page', 1),
          countItems: posts.length
        });
      });
  },

in this case, we will get 1 as a result, because limit: 1

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question