Node.js 如何使代码块同步工作

Node.js 如何使代码块同步工作,node.js,mongodb,asynchronous,express,Node.js,Mongodb,Asynchronous,Express,这是我的密码: server.get(url_prefix + '/user/:user_id/photos', function(req, res, next) { if (!req.headers['x-session-id']) { res.send({ status: { error: 1, message: "Session ID not present in request

这是我的密码:

server.get(url_prefix + '/user/:user_id/photos', function(req, res, next) {
    if (!req.headers['x-session-id']) {
        res.send({
            status: {
                error: 1,
                message: "Session ID not present in request header"
            }
        })
    } else {
        User.findOne({
            session_id: req.headers['x-session-id']
        }, function(err, user) {
            if (user) {
                var user_id   = req.params.user_id
                Album.find({userId : user_id})
                     .populate('images')
                     .exec(function (err, albums) {
                        if (albums) {
                            albums.forEach(function(album, j) {
                                var album_images   = album.images
                                album_images.forEach(function(image, i) {
                                    Like.findOne({imageID : image._id, userIDs:user._id}, function(err,like){
                                        if(like){
                                            albums[j].images[i].userLike = true;
                                        }
                                    })
                                })
                            })
                            return res.send({
                                status: {
                                    error: 0,
                                    message: "Successful"
                                },
                                data: {
                                    albums: albums
                                }
                            })
                        } else
                            return notify_error(res, "No Results", 1, 404)
                     })
            }
            else {
                res.send({
                    status: {
                        error: 1,
                        message: "Invalid Session ID"
                    }
                })
            }
        })
    }
})
我正在尝试向相册数组中的图像数组添加一个额外值(
albums[j].images[I].userLike=true;

问题是
返回res.send({
在我们从foreach获得响应之前发送数据


我如何才能使它工作,这样只有在foreach完成所有迭代后才能返回
您必须等待调用
res.send
,直到您为每个相册中的所有图像获取所有喜欢的内容

var pendingImageLikes = album_images.length;
album_images.forEach(function(image, i) {
  Like.findOne({imageID : image._id, userIDs:user._id}, function(err,like){
  if (like) {
    albums[j].images[i].userLike = true;
  }
  if (!--pendingImageLikes) {
    // we fetched all likes
    res.send(
      // ...
    );
  }
});
您可能需要使用相册图片的特殊情况。长度===0

此外,这并没有考虑到你有多个图像,每个图像都有多个图像。你必须延迟<代码> RES.Eng/<代码>,以非常类似的方式让它实际工作。你可能想考虑使用一个流控制库(或者其他任何你喜欢的,只是搜索“流控制库”)。让这更容易一点


也可以考虑不要使用分号插入和手动键入分号。它可以防止模糊的表达式,使代码更容易阅读。

< P>你必须等待调用“代码> RES.Enter <代码>,直到你获得了所有相册中所有图像的所有喜好。例如

var pendingImageLikes = album_images.length;
album_images.forEach(function(image, i) {
  Like.findOne({imageID : image._id, userIDs:user._id}, function(err,like){
  if (like) {
    albums[j].images[i].userLike = true;
  }
  if (!--pendingImageLikes) {
    // we fetched all likes
    res.send(
      // ...
    );
  }
});
您可能需要使用相册图片的特殊情况。长度===0

此外,这并没有考虑到你有多个图像,每个图像都有多个图像。你必须延迟<代码> RES.Eng/<代码>,以非常类似的方式让它实际工作。你可能想考虑使用一个流控制库(或者其他任何你喜欢的,只是搜索“流控制库”)。让这更容易一点


此外,您可能需要考虑不依赖分号插入并手动键入分号。它防止模糊表达式,使代码更易于阅读。

< P>由于您需要代码等待所有的<代码>查找< /代码>操作已完成,我建议您考虑使用包,具体地说是L。ike
each
()。它使异步循环的使用更加干净,尤其是在处理MongoDB文档和查询时。它有很多很好的特性,包括能够顺序执行一系列函数或(当您想要执行一系列,但要将结果一步一步地传递给另一步时)

添加到您的模块:

var async = require("async");
您的代码如下所示:

albums.forEach(function(album, j) {
    async.each(album.images, function(album, done) {
        Like.findOne({imageID: image._id, userIDs:user._id}, function(err, like){
            if(!err && like){
                albums[j].images[i].userLike = true;
            }
            done(err); // callback that this one has finished
        })
    })
    }, function (err) { // called when all iterations have called done()
        if (!err) {
            return res.send({
                status: {
                    error: 0,
                    message: "Successful"
                },
                data: {
                    albums: albums
                }
            });
        } 
        return notify_error(res, "No Results", 1, 404);
    });
});

因为你需要你的代码等到所有的<代码>找到操作已经完成,我建议你考虑使用这个包,具体地说,比如“代码>每个()。它使异步循环的使用变得更干净,尤其是在处理MongoDB文档和查询时。它有许多很好的功能,包括能够顺序执行一系列函数或(当您想要执行一系列,但要将结果一步一步地传递给另一步时)

添加到您的模块:

var async = require("async");
您的代码如下所示:

albums.forEach(function(album, j) {
    async.each(album.images, function(album, done) {
        Like.findOne({imageID: image._id, userIDs:user._id}, function(err, like){
            if(!err && like){
                albums[j].images[i].userLike = true;
            }
            done(err); // callback that this one has finished
        })
    })
    }, function (err) { // called when all iterations have called done()
        if (!err) {
            return res.send({
                status: {
                    error: 0,
                    message: "Successful"
                },
                data: {
                    albums: albums
                }
            });
        } 
        return notify_error(res, "No Results", 1, 404);
    });
});

概率是,对于node,如果你问“我怎样才能使这个同步”,答案是“改变你的大脑”。除了你习惯于这样工作之外,没有什么理由故意使某个东西同步。概率是,对于node,如果你问“我如何使这个同步”,答案是“改变你的大脑”.除了你已经习惯了这种工作方式之外,几乎没有理由故意让某些东西同步。