메서드 체인잉

메서드를 연속적으로 부르는 코드 - for 안에서 let 으로 curr, next 를 scope 를 for 블락 스코프로 선언 - chain 이 호출 될때 for 문이 실행될때 배정된 curr, next 가 호출됨

Input

[method1, method2]

Output

chainMethod = () => {
 methods1(req, res, (req, res) => { method2(req, res, () => {})})
}

Code

const methods = [
    (req0, res0, next) => { console.log("methods0"); next(); }, 
    (req1, res1, next) => { console.log("methods1"); next(); }
];

var j = 0;
function makechain(methods) {
    chain = () => {};
    len = methods.length;
    for (var i = len - 1 ; i >= 0; i--) {
        let curr = methods[i];
        let next = chain;
        chain = (req, res) => {
            if(++j > 10)  throw Error();
            curr(req, res, () => next(req, res));
        }
    }

    return chain;
}

chain = makechain(methods)
chain();

// # i = 1
// ## before
// chain = () => {}
// ## After
// chain = (req, res) {
//     methods[1](req, res, () => () => {})
// }
//
// # i = 0
// ## before
// chain = (req, res) { methods[1](req, res, () => () => {}) }
// ## After
// chain = (req, res) {
//     methods[0](req, res, (req, res) => { methods[1](req, res, () => () => {}) })
// }