Async.foreach迭代强制停止,直到第一次迭代执行

时间:2014-05-07 11:17:37

标签: node.js asynchronous foreach sequelize.js

    async.forEach(vsr.vehicles, function(vsr_vehicle, callback){
     pjCustom.vehicleJson(vsr_vehicle, function(vehicleInitialize){
     Vehicle.find({ where: { vehicleID: (vsr_vehicle.vehicleID).toString().trim() } }).success(function(vehicleFound){ 
      if(vehicleFound){ 
        //Code Logic is working fine.
       }else{
         vehicleBuild.save().success(function(vehicleNew){  // To create new vehicle of updated vsr
            var vehicleBuild = Vehicle.build(vehicleInitialize)
              pj.log("Update vehicle ............................")
              temp.push(vehicleNew.vehicleID)  
          })
      }
    })
})   
 callback()
  },function(){
res.send(204)
})


    //vehicleJSON
    exports.vehicleJson = function(vsr_vehicle, callback){ 
          pjCustom.getVehicle(vsr_vehicle, function(status, vehicleId){
    if (status == true) {
  vsr_vehicle.vehicleID = vehicleId
      callback(
      { 'vehicleID':vsr_vehicle.vehicleID).toString().trim(),'vsr_id':vsr_vehicle.vsr_id})
      }
    })
  }


     //getvehicle 

      exports.getVehicle = function(vsr_vehicle, callback){
      if(vsr_vehicle.vehicleID !== undefined){
       callback(true, vsr_vehicle.vehicleID)
        }else{
         Vehicle.find({ where: { 'vsr_id': vsr_vehicle.vsr_id }, 
             attributes: ['id',  'vehicleID'],'order': 'id DESC', 'limit': '1'             
     }).success(function(vehicles){
  var temp = (vehicles.vehicleID).split("-")
  var newvehicleId = temp[0]+"-"+temp[1]+"-"+(parseInt(temp[2])+1)
  callback(true, newvehicleId)
        })
   }
  }

说明:

从vsr_vehicle插入记录时

。我需要检查vehicleID是否存在,然后它将获取,否则它将创建一个新的Id。     考虑此代码用于更新车辆以及插入另外的“两个”新车辆。如何管理异步过程。插入新车辆。 它不是在等待第一次迭代的完成,而是为了两辆新车而为vehicleJson和同一车辆ID生成。建议我完成这个挑战。

我的代码清楚地写在这里。

请在阅读前请求复制代码并粘贴到任何JS编辑器中,你肯定会理解我的解释。

1 个答案:

答案 0 :(得分:1)

您在series.forEach中的回拨电话位于错误的位置。这是更正:

async.forEach(vsr.vehicles, function(vsr_vehicle, callback){
    pjCustom.vehicleJson(vsr_vehicle, function(vehicleInitialize){
        Vehicle.find({ where: { vehicleID: (vsr_vehicle.vehicleID).toString().trim() } }).success(function(vehicleFound){
            if(vehicleFound){
                callback();  // <--- call here                
            }else{
                vehicleBuild.save().success(function(vehicleNew){  // To create new vehicle of updated vsr
                    var vehicleBuild = Vehicle.build(vehicleInitialize);
                    pj.log("Update vehicle ............................");
                    temp.push(vehicleNew.vehicleID);
                    callback(); // <--- call here
                });
            }
        });
    });
    // callback();     // <--- Don't call here
},function(){
    res.send(204);
});

BTW,为了更好的做法,在javascript语句结束时使用分号(“;”)