问题描述
我正在显示集合中的一堆页面,因此为了在我的视图中可用,我在app.js
中初始化了一个全局locals
变量,如下所示:
I am displaying a bunch of pages from a collection, so to have them available in my view I initialize a global locals
variable in app.js
like so:
Page.find({}).sort({ sorting : 1}).exec(function(err, pages){
if (err) {
console.log(err);
} else {
app.locals.pages = pages;
}
});
那很好.但是,我也可以对这些页面的显示方式进行重新排序,因此在重新排序后,我会以相同的方式从上方重做Page.find()
,但这似乎总是落后一步.
That works fine. However, I also have the ability to reorder the way those pages show up, so after i do the reordering I redo the Page.find()
from above in that same route, but it seems to always be one step behind.
因此,如果我通过重新排序进行更改(将其称为reorder 1
),则此后在app.locals.pages
中看不到差异,但是如果我再次重新排序(将其称为reorder 2
,则可以看到reorder 1
排序而不是reorder 2
等等,因此基本上总是落后一步.
So if I make a change by reordering (let's call it reorder 1
), I do not see a difference in app.locals.pages
after that, but if I reorder again (let's call this reorder 2
, then I see the reorder 1
ordering and not reorder 2
and so on always, so basically it's always a step behind.
路线中的相关代码:
for (var i = 0; i < ids.length; i++) {
var id = ids[i];
count++;
(function(count) {
Page.findById(id, function (err, page) {
page.sorting = count;
page.save(function (err) {
if (err)
console.log(err);
});
});
})(count);
}
Page.find({}).sort({sorting: 1}).exec(function (err, pages) { // this is always a step behind
if (err) {
console.log(err);
} else {
req.app.locals.pages = pages;
}
});
为什么没有最新消息?
推荐答案
Okey,然后我理解了您的问题.
Okey, then I understood your problem.
问题是您的page.save
比您的for
需要更多的时间因此,在您找到之后,将获得与以前几乎相同的结果.
The problem is than your page.save
take more time than your for
So after your find will get almost the same result than before.
您在哪里使用它(for
)?在一条特殊的路线上?
Where do you use it (for
) ? in a special route ?
简单的异步javascript问题;)
Simple Asynchronous javascript problems ;)
```
function sortPages(ids, callback) {
var total = 0;
for (var i = 0; i < ids.length; i++) {
var id = ids[i];
count++;
(function(count) {
Page.findById(id, function (err, page) {
page.sorting = count;
page.save(function (err) {
++total;
if (err)
console.log(err);
if (total >= ids.length) {
callback('done');
}
});
});
})(count);
}
}
sortPages(ids, function () {
Page.find({}).sort({sorting: 1}).exec(function (err, pages) {
if (err) {
console.log(err);
} else {
req.app.locals.pages = pages;
}
});
});
```
这篇关于本地变量未正确更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!