Q.spread and pyramid of doom

筅森魡賤 提交于 2019-12-11 01:34:13

问题


I have this code:

Q.spread([
    Q.nfcall(employee.save.bind(employee)),
],function(emp){
    Q.spread([Q.nfcall(dept.save.bind(dept))],function(dept){
          console.log("success")
    },function(e){
        console.error(e);
        mongoose.disconnect();
    })
},function(e){
    console.error(e);
    mongoose.disconnect();
})

Although it works great, it starts to look like the pyramid of doom. Is there a way to refactor it to be more "promising"?

I expected something like this to be working:

Q.spread([
    Q.nfcall(employee.save.bind(employee))
]).then(function(emp){
    var dept = new Department();
    return Q.spread([
       Q.nfcall(dept.save.bind(dept))
   ])
}).then(function(dept){
        console.log("success");
}).catch(function(e){
        console.error(e);
})

but it isn't.


回答1:


Q.nfcall(employee.save.bind(employee)).spread(function(emp, numberAffected) {
    return Q.nfcall(dept.save.bind(dept));
}).spread(function(dept, numberAffected) {
    console.log("success");
    mongoose.disconnect();
}).catch(function(e) {
    console.error(e);
});


来源:https://stackoverflow.com/questions/23288206/q-spread-and-pyramid-of-doom

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!