Node.js에서 next ()를 사용하고 next ()를 반환하는시기
시나리오 : 다음은 노드 웹 앱의 코드 일부임을 고려하십시오.
app.get('/users/:id?', function(req, res, next){
var id = req.params.id;
if (id) {
// do something
} else {
next(); //or return next();
}
});
문제 : 난 그냥 함께 가야하는 하나 확인하고 next()
나 return next()
. 위의 샘플 코드는 모두 동일하게 작동하며 실행에 차이가 없었습니다.
질문 이 몇 가지 하나 개 넣어 빛이 때 사용할 수 next()
때 사용하는 return next()
몇 가지 중요한 차이점?
일부 사람들은 항상 return next()
콜백을 트리거 한 후 실행이 중지되도록하는 것입니다.
그렇게하지 않으면 나중에 콜백을 트리거 할 위험이 있으며, 결과적으로 심각한 결과를 초래합니다. 귀하의 코드는 정상이지만 다음과 같이 다시 작성합니다.
app.get('/users/:id?', function(req, res, next){
var id = req.params.id;
if(!id)
return next();
// do something
});
그것은 들여 쓰기 수준을 저장하고 나중에 코드를 다시 읽을 때 next
두 번 호출되는 방법 이 없다고 확신 합니다.
@Laurent Perrin의 답변으로 :
그렇게하지 않으면 나중에 콜백을 트리거 할 위험이 있습니다.
다음과 같이 미들웨어를 작성하는 경우 여기에 예제를 제공합니다.
app.use((req, res, next) => {
console.log('This is a middleware')
next()
console.log('This is first-half middleware')
})
app.use((req, res, next) => {
console.log('This is second middleware')
next()
})
app.use((req, res, next) => {
console.log('This is third middleware')
next()
})
콘솔의 출력은 다음과 같습니다.
This is a middleware
This is second middleware
This is third middleware
This is first-half middleware
즉, 모든 미들웨어 함수가 완료된 후 next () 아래 코드를 실행합니다.
그러나을 사용하면 return next()
즉시 콜백을 건너 뛰고 콜백 return next()
에서 아래 코드에 도달 할 수 없습니다.
next()
connect 미들웨어의 일부입니다 . 라우터 흐름에 대한 콜백은 당신이 당신의 기능에서 아무것도 반환 그래서 만약, 상관하지 않는다 return next()
와 next(); return;
기본적으로 동일합니다.
In case you want to stop the flow of functions you can use next(err)
like the following
app.get('/user/:id?',
function(req, res, next) {
console.log('function one');
if ( !req.params.id )
next('No ID'); // This will return error
else
next(); // This will continue to function 2
},
function(req, res) {
console.log('function two');
}
);
Pretty much next()
is used for extending the middleware of your requests.
Next() :
Calling this function invokes the next middleware function in the app. The next() function is not a part of the Node.js or Express API, but is the third argument that is passed to the middleware function.
참고URL : https://stackoverflow.com/questions/16810449/when-to-use-next-and-return-next-in-node-js
'programing tip' 카테고리의 다른 글
예외 코드“EXC_I386_GPFLT”의 의미는 무엇입니까? (0) | 2020.07.29 |
---|---|
C ++ 헤더에서 "네임 스페이스 사용" (0) | 2020.07.29 |
boto3를 사용하여 S3 객체를 파일에 저장하는 방법 (0) | 2020.07.28 |
WebView 내부에 외부 웹 페이지를로드하는 방법 (0) | 2020.07.28 |
SQL에서 NULL 또는 빈 문자열을 사용하는 방법 (0) | 2020.07.28 |