Promise是现在用于写异步很好的方式,所有能用promise的地方就一定用,不然你的代码就会嵌套的越来越深。但是我们也会遇到promise的then里面还会是一个异步函数。这个时候就的注意了。
doSomeAsyncOperation(param, function(err, result) {
if (err) {
return handleError(err);
}
return anotherAsync(result, function(err, something) {
if (err) {
return handleSpecificError(err);
}
var nextArg = syncOp(something);
return anotherCallbackedOperation(nextArg, function(err, whatever) {
if (err) {
return handleError(err);
}
return youCanSeeWhereItIsGoing(whatever, function(err, yeah) {
if (err) {
return handleError(err);
}
return toBeautifulChristmasTree(yeah, function(err, bummer) {
if (err) {
return handleError(err);
}
return soHardToReadAndThisHasOnlyLinearFlow(bummer);
});
});
});
});
});
可以改成这样的
doSomeAsyncOperation(param)
.then(anotherAsync)
.then(function(something) {
return anotherPromisifiedOperation(syncOp(something));
})
.then(nowYouCanSee)
.then(thatThisIsMuchEasierToRead)
.then(andFollow)
.then(especiallyWhenYouDefineAllStepsAsSeparateFunctions)
.then(thereIsNoChristmasTreeAtTheEnd)
.catch(specificError, alsoErrorsAreEasierToHandle)
.catch(asYouCanHandleThemAlsoInGenericWay);
下面这个是实际项目中的例子:
function getHwUnitName() {
return onlineImTree.getImTree()
.then(imTree => {
return nodeFinder.getActiveBtsLNode(imTree)
.then(activeBtsLNode => ({imTree, activeBtsLNode}));
})
.then(getHwUnitNameFromBpfByProductCode);
}