NodeJs初始化函数内的数组
我决定在我的nodejs项目中使用句柄,因此对于索引页面,我希望收集与post,页面,类别等有关的所有信息。
我有一个函数,如下所示从数据库返回post;
exports.getPosts = function(req, res){ Posts.find({}, function(err, posts) { var postsMap = {}; if (err){ res.status(400); } else{ posts.forEach(function(post) { postsMap[post._id] = post; }); res.jsonp(postsMap); } }); };
我想把这个function改成下面的原型。
function getPosts(req, res){ var posts = [ { "url": "#", "title": "home!", "content": "home desc" }, { "url":"#2", "title": "about", "content": "about desc)" } ] return posts; }
我已经尝试了类似下面的代码,但职位数组未被初始化,并返回undefined;
function getPosts(req, res){ var posts = []; Posts.find({}, function(err, posts) { var postsMap = {}; if (err){ res.status(400); } else{ posts.forEach(function(post) { postsMap[post._id] = post; }); posts.push(postsMap); } }); return posts; }
我该如何处理这个问题?
在最后一段代码中,传递给Posts.find
的函数在函数返回之前不会运行
执行的顺序是(见注释):
function getPosts(req, res){ var posts = []; //// 1 Posts.find({}, function(err, posts) { var postsMap = {}; //// 3 if (err){ res.status(400); } else{ posts.forEach(function(post) { postsMap[post._id] = post; }); posts.push(postsMap); } }); return posts; // 2 }
这是因为Javascript是asynchronous的,不会等待Post.find
完成对数据库的调用。 相反,它会继续下去,稍后会调用function(err, posts)
。
通常要解决这个问题,我们给你的函数callback。 你的代码可以被重构为:
function getPosts(callback){ // Note that i removed res, req from this as it is good practice to separate out request handling from data fetching. Instead I moved it to the usage function mentioned later Posts.find({}, function(err, posts) { var postsMap = {}; if (err){ callback(err); } else{ posts.forEach(function(post) { postsMap[post._id] = post; }); callback(null, postsMap); } }); }
当你使用getPosts
,你可以这样做:
function otherFunction(req, res){ getPosts(function(err, postsMap){ // This will start running once getPosts is done if(err) res.status(400); else res.jsonp(postsMap); }) // This runs almost immediately and before getPosts is done }
如果我明白,你想Post.find()
函数results
variables,真?
问题1:你的callback有两个参数,第二个是posts
。
这创build了一个只能在callback中使用的variables,所以你不能访问getPosts()
函数中的variables。
你所做的function只是返回一个空的数组,因为你不能访问它。
问题2:你试图同步返回一个值,但是你正在使用一个asynchronous函数。
这是一个应该工作的示例代码:
function getPosts(req, res, callback) { var glob_posts = []; Posts.find({}, function(err, posts) { var postsMap = {}; if(err) res.status(400); else { posts.forEach(function(post) { postsMap[post._id] = post; }); glob_posts.push(postsMap); callback(glob_posts); } }); }
你可以通过这种方式使用这个function:
getPosts(req, res, function(posts) { // The 'posts' variable contains current posts });
我希望帮助你:)