비동기(callback, promise, async/await, fs.readFile)

Jamie·2021년 8월 9일
post-thumbnail

callback 함수

다른 함수의 매개변수로 함수를 전달하고, 어떠한 이벤트가 발생한 후 매개변수로 전달한 함수가 다시 호출되는 것

callback in action: 반복 실행하는 함수(iterator)

[1, 2, 3].map(function(element, index){
  return element * element;
})

callback in action: 이벤트에 따른 함수(event handler)

document.querySelector('#btn').addEventListener('click', function(e){console.log('button clicked')       
})

비동기

:요청에 대한 결과가 동시에 일어나지 않는다

  1. DOM element의 이벤트 핸들러
    • 마우스, 키보드 입력(click, keydown)
    • 페이지 로딩(DOMContentLoaded)
  2. 타이머
    • 타이머 API(setTimeout등)
    • 애니메이션 API(requestAnimationFrame)
  3. 서버에 자원 요청 및 응답
    • fetch API
    • AJAX(XHR)

비동기 함수 전달 패턴

  1. callback 패턴
let request = 'caffelatte'
orderCoffeeAsync(request, function(response){
  //response -> 주문한 커피 결과
  drink(response)
})
  1. 이벤트 등록 패턴
let request = 'caffelatte'
orderCoffeeAsync(request).onready = function(response){
  //response => 주문한 커피 결과
  drink(response)
}

Callback

const printString = (string, callback) => {
  setTimeout(
    () => {
      console.log(string)
      callback()
    },
    Math.floor(Math.random() * 100) + 1
    )
}
const printAll = () => {
  printString("A", () => {
    printString("B", () => {
      printString("C", () => {}}
                  })
  })
}
printAll()

Promise

const printString = (string) => {
  return new Promise((resolve, reject) => {
  setTimeout(
    () => {
      console.log(string)
      resolve()
    },
    Math.floor(Math.random() * 100) + 1
    )
})
}
const printAll = () => {
  printString("A") 
  .then(() => {
    return printString("B")
  })
  .then(() => {
     return printString("C") 
                  })
}
printAll()

async await

function gotoCodestates(){
  return new Promise((resolve, reject) => {
    setTimeout(() => {resolve('1. go to codestates')}, 100)
  })
}
function sitAndCode(){
  return new Promise((resolve, reject) => {
    setTimeout(() => {resolve('2. sit and code')}, 100)
  })
}
function eatLunch(){
  return new Promise((resolve, reject) => {
    setTimeout(() => {resolve('3. eat lunch')}, 100)
  })
}
function goToBed(){
  return new Promise((resolve, reject) => {
    setTimeout(() => {resolve('4. goToBed')}, 100)
  })
}
const result = async () =>{
  const one = await gotoCodestates();
  console.log(one)
  const two = await sitAndCode();
  console.log(two)
  const three = await eatLunch();
  console.log(three)
  const four = await gotoBed();
  console.log(four)

fs.readFile

(path, [options], callback)
:로컬에 존재하는 파일을 읽어오는 메소드
비동기적으로 파일 내용 전체를 읽고 이 메소드를 실행할 때는 인자 3개를 넘길 수 있음

path\string\Buffer\URL\

  • path에는 파일 이름을 인자로 넘길 수 있음(일반적으로 문자열 타입)
    fs.readFile('/etc/passwd', ..., ...)```
    

options\Object\string

options는 넣을 수도 있고, 넣지 않을 수도 있고 객체 형태 또는 문자열로 넘길 수 있음

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

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

#### callback \<Function>
콜백 함수를 전달하며 파일을 읽고 난 후에 비동기적으로 실행되는 함수
두가지 파라미터가 존재하는데
1. 에러가 발생하지 않으면 err는 null이 되며,
2. data(파일의 내용)에 문자열이나 Buffer라는 객체가 전달됨
```js
fs.readFile('test.txt', 'utf8', (err, data) => {
if (err) {
  throw err; // 에러를 던집니다.
}
console.log(data);
}); ```

profile
공부하고 비행하다 개발하며 여행하는 frontend engineer

0개의 댓글