Question

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.

Was it helpful?

Solution

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);
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top