비동기

»

비동기

요청에 따른 결과 = 동기

요청에 대한 결과가 동시에 일어나지 않음 = 비동기

비동기 함수 전달패턴

  • callback 패턴

    let request = 'caffelatte';
    orderCoffeAsync(request, function(response) {
    	// response -> 주문한 커피 결과
    	drink(response);
    };
    
  • 이벤트 등록 패턴

    let request = "caffelatte";
    orderCoffeAsync(request).onready = function (response) {
      // response -> 주문한 커피 결과
      drink(response);
    };
    

callback

const printString = (string, callback) => {
  setTimeout(() => {
    console.log(string);
    callback();
  });
};

const printAll = () => {
  printString("A", () => {
    printString("B", () => {
      printString("C", () => {});
    });
  });
};

printAll(); // now what do you expect?

fs.readFile

fs.readFile 은 로컬에 존재하는 파일을 읽어옵니다

fs.readFile(Path[, options], callback)
// 대괄호는 선택적인자를 의미합니다

메소드 fs.readFile 은 비동기적으로 파일 내용 전체를 읽습니다

인자

path 에는 파일 이름을 인자로 넘길 수 있습니다 네가지 종류의 타입을 넘길 수 있지만 일반적으로는 문자열의 타입으로 넘깁니다

path \<string> |\<Buffer> |\<URL>|\<integer>

// ex
fs.readFile('/etc/password', ..., ...)

options 넣을 수도 있고 넣지 않을수도 있습니다

options \<Object> |\<string>

// ex
let options = {
	encoding: 'utf8', // UTF-8이라는 인코딩 방식으로 엾니다
	flag: 'r', // 읽기 위해 엽니다
}

// /etc/passed 파일을 옵션을 사용하여 읽습니다
fs.readFile('/etc/passwd', options, ...)

callback 콜백함수를 전달합니다 파일을 읽고 난 후에 비동기적으로 실행되는 함수입니다

callback \<Function>
	err \<Error>
	data \<string> |\<Buffer>

// 에러가 발생하지 않으면 err는 null이 되고 data에는 문자열이나 Buffer라는 객체가 전달됩니다
// data === 파일의 내용