简体   繁体   English

多个异步函数调用

[英]Multiple asynchronous function calls

given the situation there is an action inside a NodeJs server (in my case SailsJs) where I need to create x different entities in one call. 考虑到这种情况,NodeJs服务器(在我的情况下为SailsJs)内部有一个动作,我需要在一个调用中创建x个不同的实体。 It is not possible for the client to call the action x times. 客户不可能调用动作x次。 What is the best/recommended way of creating these entities regarding callbacks. 关于回调创建这些实体的最佳/推荐方式是什么? If I understood callbacks right it is not possibile to just built something like this: 如果我正确理解了回调,则不可能仅构建如下所示的内容:

for(var i = 0; i < x; i++){
  User.create(...).exec(...);
}

What would be the right way to implement this? 什么是实现此目标的正确方法?

Bruno 布鲁诺

Easy do it with async package 使用异步包轻松完成

var async = require('async');
async.times(x, function(n, next){
    User.create(...).exec(function(err, user) {
      next(err, user)
    })
}, function(err, users) {
  // processed x times 
});

You can hand over an array of to be created users to User.create . 您可以将要创建的用户数组User.createUser.create You prepare the array of users first. 您首先准备一组用户。

With lots of users to be created having some many-to-many relationships, native calls are much faster, eg Mongo bulk inserts. 由于要创建的许多用户具有多对多关系,因此本地调用要快得多,例如Mongo批量插入。

Sails Reference regarding create 关于创建的Sails参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM