2016-03-03 98 views
1

有没有办法避免使用'q'下面的代码嵌套链接,任何好的方式来使用承诺?承诺使用nodejs和sequelize

global.models.test.destroy({ 
     where: { 
      id: req.params.id 
     } 
    }).then(function() { 
     global.models.test1.findAll({ 
       attributes:[['id','testId']], 
       include:[{ 
        model: global.models.test2, 
        where: { 
         masterId: req.params.id 
        }, 
        required: true 
       }] 
     }).then(function(app){ 
      var arrIds =[]; 
      for(var result in app){ 
       var collection = app[result].dataValues; 
       arrIds.push(collection.id); 
      } 

      global.models.test1.destroy({ 
       where: { 
        id: arrIds 
       } 
      }).then(function() { 
       global.models.destroy({ 
        // nested loops again and so on 
       }): 
      }))); 

我正在寻找通过避免嵌套循环来清理代码的方法。欢迎所有帮助

回答

0

是的,只需从您的then返回您的承诺。

global.models.test.destroy({ 
    where: { 
     id: req.params.id 
    } 
}).then(function() { 
    return global.models.test1.findAll({ 
     attributes:[['id','testId']], 
     include:[{ 
      model: global.models.test2, 
      where: { 
       masterId: req.params.id 
      }, 
      required: true 
     }] 
    }) 
}).then(function(app) { 
    var arrIds = []; 
    for(var result in app) { 
     var collection = app[result].dataValues; 
     arrIds.push(collection.id); 
    } 
    return global.models.test1.destroy({ 
     where: { 
      id: arrIds 
     } 
    }); 
}).then(function() { 
    return global.models.destroy({ 
     //and so on 
    }); 
}); 

我也想避免污染global变量。