我有一个包含大量嵌套回调的代码块。我对代码重构感兴趣,使其更具可读性并避免代码膨胀。有人可以提一下如何将以下代码转换为承诺。我想做一个比较,看看它是否值得在代码中应用promises的努力实现这样的代码回调
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);
}
});
});
});
});
答案 0 :(得分:0)
更喜欢 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??
}
}
可以这样:
optimised().then(function(){
console.log("sucess");
},function(error){
console.error(error);
});
请注意,所有dataApi方法都需要返回promises才能使其正常工作......