Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

9시 24분

함수를 이용한 정리 정돈, 동기와 비동기, call back 본문

Javascript/Node.js

함수를 이용한 정리 정돈, 동기와 비동기, call back

leeeee.yeon 2021. 5. 5. 20:54
함수를 이용한 정리정돈

함수를 이용해서 main.js를 리팩토링하자.

 

function templateHTML(title, list, body){
    return `
    <!doctype html>
    <html>
    <head>
      <title>WEB1 - ${title}</title>
      <meta charset="utf-8">
    </head>
    <body>
      <h1><a href="/">WEB</a></h1>
      ${list}
      ${body}
    </body>
    </html>
    `;
}

function templateList(fileList){
    var list = '<ul>';
    var i = 0;
    while(i < fileList.length){
      list = list + `<li><a href="/?id=${fileList[i]}">${fileList[i]}</a></li>`;
      i = i + 1;
    }
    list = list + '</ul>';

    return list;
}

위와 같이 함수를 만들어주고, 해당하는 부분을 아래와 같이 바꾸자.

var list = templateList(fileList);
var template = templateHTML(title, list,`<h2>${title}</h2>${description}`);

 

동기와 비동기

동기적: 순차적으로 일을 진행, 하나 끝나구 하나

비동기적: 병렬적으로 일을 진행, 하나를 하면서 동시에 다른 일도 함

 

// sync

var fs = require('fs');

console.log('a');
var result = fs.readFileSync('syntax/sample.txt', 'utf8');
console.log(result);
console.log('c');

 

//async

var fs = require('fs');

console.log('a');
fs.readFile('syntax/sample.txt', 'utf8', function(err,result){
    console.log(result);
}); // sync 안 붙으면 비동기적으로 실행하는 것 선호
console.log('c');

fs.readFile() : 파일을 읽고 함수를 실행한다. 첫번째 매개변수는 에러, 두번째 매개변수는 파일의 내용을 인자로 제공

결과 해석 : a -> c 바로 동작, b는 b대로 동작하다가 끝나면 함수가 호출되어 나중에 실행