我正在尝试了解如何异步或承诺或任何使我的代码更好的东西。这是我的代码的一个例子
Bus.findOne({_id: bus_id}, function (err, bus) {
if (err) {
res.json({status: "error", message: "please enter a valid bus_id"});
return;
}
bus.language = record.language ? record.language : bus.language;
bus.bus_number = record.bus_number ? record.bus_number : bus.bus_number;
bus.bus_driver = bus_driver ? bus_driver : bus.bus_driver;
bus.bus_details = bus_details ? bus_details : bus.bus_details;
bus.trips = record.trips ? record.trips : bus.trips;
bus.location = record.location ? record.location : bus.location;
bus.save(function (err, bus) {
if (err) {
res.json({status: "error", error: errors, message: "bus wasn't saved"});
return;
} else {
User.findOne({refid:bus_id},function(err,doc){
if (err) {
res.json({status: "error", error: "bus user update was not saved"});
return;
} else if(doc){
doc.name = "bus number"+ '' + bus.bus_number;
doc.refid = bus.id;
doc.save(function(err){
if (err) {
res.json({status: "error", error: "bus user update was not saved"});
return;
}else{
res.json({status: "success", message: "bus was successfully updated", bus: bus});
return;
}
});
}else{
res.json({status:"error",message:"an error with finding user"});
return;
}
});
}
});
});
这就是我最终的结果
Bus.findOne({_id:bus_id}).exec().then(function(bus){
bus.language = record.language ? record.language : bus.language;
bus.bus_number = record.bus_number ? record.bus_number : bus.bus_number;
bus.bus_driver = bus_driver ? bus_driver : bus.bus_driver;
bus.bus_details = bus_details ? bus_details : bus.bus_details;
bus.trips = record.trips ? record.trips : bus.trips;
bus.location = record.location ? record.location : bus.location;
return bus.save().exec();
}).then(function(bus){
return User.findOne({refid:bus._id}).exec();
}).then(function(doc){
doc.name = "bus number"+ '' + bus.bus_number;
doc.refid = bus.id;
return User.save().exec();
}).then(function(){
res.json({status:"success",message:"bus and associated user has been removed"});
}).catch(function(error){
res.json({status:"error",message:"an error with finding user"});
});
但是服务器一直在捕捉错误,我知道我做错了什么但我不知道错误在哪里