[JS] Asynchrounous & Promise

ds-k.fe·2021년 6월 13일
0

JavaScript

목록 보기
9/14

20200315 기록

Asynchoronus JavaScript

1. why Async

  • Synchoronus - 동기적인

    클라이언트가 서버에 요청을 하고 나서 응답이 올때까지 기다렸다가 진행

  • Asynchoronous - 비동기적인
    클라이언트가 서버에 요청을 하고 나서 기다리지 않고 다른 일을 하다가, 응답이 오면 그것을 진행
    → 효율이 좋다

  • Client - '서버로 접속하는 컴퓨터' ex) 본인의 컴퓨터

  • Server - '무언가(서비스, 리소스 따위)를 제공하는 컴퓨터' ex) 웹 서버, 게임 서버

2. Callback

  • Async를 핸들할수 있는 것
const printString = (string) => {
    setTimeout(
        () => {
            console.log(string);
        },
        Math.floor(Math.random() * 100) + 1
    )
}

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

// => printAll이 비동기적으로 실행되지만, 순서를 제어할 수 없다.
const printString = (string, callback) => {
    setTimeout(
        () => {
            console.log(string);
            callback();
        },
        Math.floor(Math.random() * 100) + 1
    )
}

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

// => Callback()을 통해, 비동기적 실행 순서를 제어할 수 있다.

3. Promise

  • new Promise()를 통해서, 새로운 인스턴스 생성
    → resolve() - 다음 액션으로 넘어가거나
    → reject() - 에러를 핸들링
const printString = (string) => {
    //callback을 인자로 받지 않고, 새로운 Promise를 리턴
    return new Promise((resolve, reject) => {
        setTimeout(
            () => {
                console.log(string);
                resolve();
            },
            Math.floor(Math.random() * 100) + 1
        )
    })
}

const printAll = () => {
    // .then -> 앞의 동작이 끝나면 뒤의 callback을 실행해줘
    printString("A")
    .then(() => {
        return printString("B")
    })
    .then(() => {
        return printString("C")
    })
}
printAll()
function gotoHome(){
  return new Promise((resolve, reject) => {
    setTimeout(() => {resolve("1. go to home"), 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. go to bed"), 100})
  })
}

4. async await

  • Promise의 Syntatic Suger
function gotoHome(){
    return new Promise((resolve, reject) => {
        setTimeout(() => {resolve("1. go to home"), 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. go to bed"), 100})
    })
}

//표현 자체를 동기적으로 쓸 수 있어서, 훨씬 더 코드 가독성이 좋아진다.

0개의 댓글