Answer the question
In order to leave comments, you need to log in
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
});
});
},
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
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 и его лучше не использовать, имхо
})
}
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
});
});
},
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question