简体   繁体   English

Node.js函数中的异步混乱

[英]Async confusion in nodejs function

I always have multiple operations in one route or endpoint. 我总是在一个路由或端点中进行多项操作。 Take an example below, when a user deletes an item, I want the related file be deleted in s3 too besides deleting related collection from the database. 下面举个例子,当用户删除一个项目时,除了从数据库中删除相关集合外,我也希望在s3中也删除相关文件。

So is the code below ok? 那么下面的代码可以吗? Does it matter if I put the first function (delete file from s3) inside the DeleteItem function? 是否将第一个函数(从s3中删除文件)放在DeleteItem函数中,这有关系吗?

router.post('/item/delete', function(req, res) {

  if(req.body.dlt_item){

        var tempArray = [];
        tempArray.push({"Key":req.body.dlt_item});

        s3Bucket.deleteObjects({
              Bucket: 'myS3',
              Delete: {
                  Objects: req.body.dlt_item
              }
          }, function(err, data) {
              if (err) 
                return console.log(err);
        });
      }

  Item.DeleteItem(req.body.item_id, function(err,result){
    if(err){console.log(err)}
    res.send({result:1});
  })
});

You should organise your code like this. 您应该像这样组织代码。 This will ensure that s3 deletion will start only when mongodb deletion has finished. 这将确保仅在mongodb删除完成后才开始s3删除。 In your code both things happen simultaneously. 在您的代码中,这两种情况同时发生。 this may cause issue in some cases. 在某些情况下,这可能会导致问题。 If one fails and other succeeds then there will be trouble. 如果一个失败而其他成功,那就会有麻烦。
Suppose s3 files get deleted successfully and mongo deletion fails. 假设s3文件成功删除,而mongo删除失败。 Then you will have many references to non existing resources. 然后,您将有许多对不存在的资源的引用。

 router.post('/item/delete', function(req, res) {

if(req.body.dlt_item){
    var tempArray = [];
    tempArray.push({"Key":req.body.dlt_item});
 Item.DeleteItem(req.body.item_id, function(err,result){
   if(err)
   {
     console.log(err)
     res.send(err);
   }
  else
   {
          //deletion from mongodb is succesful now delete from s3
           s3Bucket.deleteObjects({
           Bucket: 'myS3',
           Delete: {
              Objects: req.body.dlt_item
           }
         },function(err, data) {
           if (err) 
           {
             // deletion from s3 failed you should handle this case
             res.send({result:1});
             return console.log(err);
           }
           else
             {
                // successful deletion from both s3 and mongo. 
               // If you do not want to wait for this then send the response before this function.
               res.send({result:1});
             }
        });
   }      
  })
});

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

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