1

I have a code block with alot of nested callbacks. I am interested in code refactor to make it more readable and avoid the code bloat. Can someone please mention how can I convert the below code to promises. I want to do a comparison to see if its worth the effort applying promises across the code where such code callbacks are implemented

dataApi.getClientEntityByCtnId(Number(key), function (error, client1) {
    if (error) return callback(error, null);
    if (client1.id == 0)
        return callback("unregistered client:"+ key, null);
    dataApi.getClientEntityByCtnId(Number(key2), function (error, client2) {
        if (error)
            return callback(error, null);
        if (client2.id == 0)
            return callback("unregistered client:" + key2, null);

        dataApi.setClientRelationshipEntity(client1.id, client2.id, function (error) {
            if (error) return callback(error, null);                        
            dataApi.setClientRelationshipEntity(client2.id, client1.id, function (error) {
                nbCRpushed++;
                if (nbCRpushed%1000==0)  dataApi.logger.info("nb CR pushed into BC ="+nbCRpushed+"/" + dataApi.nbCR);
                if (error) return callback(error, null);

                if (nbCRpushed == dataApi.nbCR)
                {
                    dataApi.pushCRToCache(callback);
                }
            });
        });
    });
});
Asif
  • 393
  • 9
  • 17
  • 1
    Have you read [How do I convert an existing callback API to promises?](https://stackoverflow.com/q/22519784/1048572)? – Bergi Jun 23 '17 at 14:57

1 Answers1

0

Even more fancy with async/await :

async function optimised(){
  var client1 = await dataApi.getClientEntityByCtnId(+key);
  if (client1.id == 0)
    throw new Error("unregistered client:"+ key);
 var client2 = await dataApi.getClientEntityByCtnId(+key2);
 if (client2.id == 0)
    throw new Error("unregistered client:" + key2);

 await dataApi.setClientRelationshipEntity(client1.id, client2.id);   
 await dataApi.setClientRelationshipEntity(client2.id, client1.id);   

 //i think the code below is broken now... more info needed to make it work asyncly
 nbCRpushed++;
 if (nbCRpushed%1000==0)  dataApi.logger.info("nb CR pushed into BC ="+nbCRpushed+"/" + dataApi.nbCR);
 if (nbCRpushed == dataApi.nbCR){
                dataApi.pushCRToCache(callback);//um callback? what should we do here??
}
}

Usable like this:

optimised().then(function(){
   console.log("sucess");
},function(error){
  console.error(error);
});

Note that all dataApi methods need to return promises to make this work...

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151