이 맛의 사소한 Node.js 자바 스크립트 콜백 지옥을 피하려고합니다.
긴 비동기 프로세스 A 또는 B를 수행 한 다음 항상 C를 따라야합니다. psuedocode에서 :
function example(flag, callback) {
if (flag) {
doLongProcessA(function(err, result) {
if (err) return callback(err);
doLongProcessC(result, function(err, finalResult) {
if (err) return callback(err);
return callback(null, finalResult);
});
});
} else {
doLongProcessB(function(err, result) {
if (err) return callback(err);
doLongProcessC(result, function(err, finalResult) {
if (err) return callback(err);
return callback(null, finalResult);
});
});
}
}
두 개의 'doLongProcessC'호출은 매우 DRY가 아닙니다. 차라리 함수를 두 부분으로 나누지 않겠습니다 (하나는 A 또는 B, 다른 하나는 호출 할 C). Node 패키지 'async'가이 문제를 해결할 수있는 것처럼 느껴지지만 방법을 모르겠습니다. 누구든지 예제 솔루션을 줄 수 있습니까? 감사!
예, 비동기는 코드에서 콜백 지옥을 피하는 좋은 선택입니다.
async.waterfall은 "파이프 라인"의 모든 함수가 결과를 다음 함수에 전달할 수 있도록합니다.
귀하의 예에서 A와 B는 모두 결과를 다음 함수 C로 전달합니다.
다음과 같이 비동기 폭포를 사용할 수 있습니다.
function example(flag, next) {
async.waterfall(
[
function(callback) {
if (flag) {
doLongProcessA(callback);
} else {
doLongProcessB(callback);
}
},
// If you want to differentiate the behavior of C in terms of flag,
// uncomment the flag param below
function(/*flag,*/ result, callback) {
doLongProcessC(/*flag,*/ result, callback);
}
],
// if any function in the pipeline throws an err,
// it will immediately call this final function and return
function(err, result) {
if (err!= null) {
// put error handlers here
return next(err);
}
// return the result
return next(null, result);
}
};
}
doLongProcessA 및 doLongProcessB는 다음과 같아야합니다.
doLongProcessAorB(callback)
{
if (err) return callback(err, null)
// do something here to fetch the result
callback(null, /*flag, */ result);
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다