programing

Node.js에서 next()를 사용하고 next()를 반환할 때

iphone6s 2023. 8. 25. 23:24
반응형

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()그리고 중요한 차이점은?

@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

즉, 모든 미들웨어 기능이 종료된 다음() 아래 코드를 실행합니다.

하지만, 만약 당신이return 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두 번 호출됩니다.

next()는 연결 미들웨어의 일부입니다.라우터 흐름에 대한 콜백은 함수에서 반환되는 것이 무엇이든 상관하지 않습니다.return next()그리고.next(); return;기본적으로 동일합니다.

사용할 수 있는 기능의 흐름을 중지하려는 경우next(err)다음과 같이

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'); 
    }
);

어느 정도는.next()요청의 미들웨어를 확장하는 데 사용됩니다.

next()와 return next()의 차이는 다른 프로그래밍 원리로 매우 간단합니다.코드의 일부 행은 아래에 설명되어 있습니다.

    app.use((req, res, next) => {
       console.log('Calling first middleware');
       next();
       console.log('Calling after the next() function');
    });


    app.use((req, res, next) => {
       console.log('Calling second middleware');
       return next(); // It returns the function block immediately and call next() function so the return next(); and next(); return; are the same
       console.log('After calling return next()');
    });

출력은

첫 번째 미들웨어 호출
다음() 함수 뒤에 호출
보조 미들웨어 호출

import express from "express"
  
const app = express()
// API for the testing of next() 
app.get(
  '/next', function (req,res,next) { 
    console.log('hi there ');
    next();
    console.log('you are still here');
  }
)
  
// API for the testing of return next() 
app.get(
  '/return-next', function (req,res,next) { 
    console.log('hi there');
    return next(); 
    console.log('you are still here');
  }
)
  
app.listen(5000,()=> {
  console.log("App is running on port 5000")
})

next()/**next**루트는 미들웨어를 호출하고 미들웨어가 실행된 후 호출된 위치로 돌아와 나머지 코드를 실행합니다(함수 호출과 동일).

출력:

hi there

you are still here

/**return-next**경로 앞에 리턴이 있습니다.next()그러면 컨트롤러가 반환됩니다.

출력:

hi there 

을 생각하면next()함수 호출처럼 당신은 그것을 제대로 이해할 수 있었습니다.

로니의 예는 꽤 좋습니다.그러나 출력은 다음과 같습니다.

번째 호출하기
번째 호출하기
합니다.

언급URL : https://stackoverflow.com/questions/16810449/when-to-use-next-and-return-next-in-node-js

반응형