的NodeJS /水线,需要等待响应之前多次重复创建结束 [英] NodeJS/Waterline, Need to wait for multiple create end before response

查看:462
本文介绍了的NodeJS /水线,需要等待响应之前多次重复创建结束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序的NodeJS(使用sailsjs),我用一个控制器来接收一个.zip上传多张图片,然后我将它们保存在我的数据库使用水线:

In my nodejs app (using sailsjs), I use a controller to receive multiple images uploaded in a .zip, then I save them in my database using waterline:

var images = [];
zipEntries.forEach(function(zipEntry) {
    zip.extractEntryTo(zipEntry.entryName, p, false, true);

    Image.create({
        filename: zipEntry.name,
    }).exec(function(err, image){
        images.push(image);
    });
});
res.json(images);

问题是我需要发回IDS生成(自动递增)中的所有图像,但create方法是异步的。结果有没有办法等待所有create方法结束之前,我可以向服务器发送的响应?

The problem is I need to send back all the Image Ids generated (auto incremented), but the create method is asynchronous.
Is there any way to wait for all create method end before I can send the server response ?

编辑:所以我发现周围的工作通过检查,我得到的,并增加在.exec方法索引图像的数量,我可以检查,如果这是最后的EXEC,然后发送响应

var images = [],
    nbValidImage = 0,
    i = 0;
zipEntries.forEach(function(zipEntry) {
    zip.extractEntryTo(zipEntry.entryName, p, false, true);
    nbValidImage++;
    Image.create({
        filename: zipEntry.name,
    }).exec(function(err, image){
        i++;
        images.push(image);
        if(i == nbValidImage) {
            res.json(images);
        }
    });
});

但如果有人有更好的解决方案...:)

But if someone has a better solution... :)

推荐答案

在这种情况下,我会去的 async.each ,因为 zipEntries 是一个集合(没有测试此code):

In this case, I would go with async.each, since zipEntries is a collection (didn't test this code):

var async = require('async');

async.each(zipEntries, function (zipEntry, callback) {
  zip.extractEntryTo(zipEntry.entryName, p, false, true);

  Image.create({
    filename: zipEntry.name
  }).exec(function (err, image) {
    images.push(image);
    callback();
  });

}, function (err) {
  if (error) throw new Error(error);
  res.json(images);
});

这篇关于的NodeJS /水线,需要等待响应之前多次重复创建结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆