
코드스테이즈 41기 교육 내용을 정리하고 있습니다.
틀린 부분이 있으면 댓글로 알려주시면 감사하겠습니다.
🐉Asynchronous (비동기)

🐊blocking non-blocking
blocking
- 요청에 대한 결과가 동시에 일어난다. (synchronous)
non-blockinig
- 요청에 대한 결과가 동시에 일어나지 않는다. (asynchronous)
🐊Callback
Async에서 순서를 제어하고 싶을때, collback을 사용한다,
const printString = (string) =>{
setTimeout(
()=>{
console.log(string)
},
Math.floor(Math.random()*100)+1
)
}
const printAll = () => {
printString("A")
printString("B")
printString("C")
}
printAll ()
setTimeout이란
setTimeout()
setTimeout 메서드는 만료후 함수나 지정한 코드 조각을 실행하는 타이머를 설정합니다.
let timeoutID = setTimeout(function[, delay]);
function
- 타이머 완료 이후 실행할 함수
delay
- 주어진 함수 또는 코드를 실행하기 전에 기다릴 밀리초 단위 시간입니다. 생략하거나 0을 지정할 경우 "즉시", 정확하게는 다음 이벤트 사이클에 실행된다는 뜻이다
다음 코드는 실행 할때 마다 다른 값을 출력한다.
ex) B,C,A / A,C,B / C,B,A ...
순차적으로 진행 되지 않는다.
비동기 적으로 실행 되기 때문이다.
그래서 콜백 개념이 생기게 되었다.
const printString = (string, callback) => {
setTimeout(
() => {
console.log(string)
callback()
},
Math.floor(Math.random() * 100) + 1
)
}
const printAll = () => {
printString("A", () => {
printString("B", () => {
printString("C", () => {
})
})
})
}
printAll()
다음 코드는 실행 할때 마다 같은 값을 출력한다.
A,B,C
비동기 적으로 실행되는 코드를 순차적으로 진행할수 있다.
코드가 길어지면 관리하기 나빠진다.
const printAll = () => {
printString("A", () => {
printString("B", () => {
printString("C", () => {
printString("A", () => {
printString("B", () => {
printString("C", () => {
printString("A", () => {
printString("B", () => {
printString("C", () => {
})
})
})
})
})
})
})
})
})
}
printAll()
collback hell이라 부른다.
비동기함수의 순서를 제어하고 싶을 때 collback을 이용할 수 있다.
🐊Promise
collback hell을 해결할 수 있다.
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()
다음 코드는 실행 할때 마다 같은 값을 출력한다.
A,B,C
return 처리를 잘 하지 못하면 collback hell처럼 promise hell을 만날수 있다.
promise chining의 중요성!
🐊async await
const printString = (string) => {
return new Promise((resolve, reject) => {
setTimeout(
() => {
resolve(string)
},
Math.floor(Math.random() * 100) + 1
)
})
}
const printAll = async () => {
const A = await printString("A")
console.log(A)
const B = await printString("B")
console.log(B)
const C = await printString("C")
console.log(C)
}
printAll()
async await를 사용하면 동기 함수를 사용하는것 처럼 순차적으로 출력을 할수 있고, promise보다 일반함수 처럼 하용할 수 있다.
🦦잡담
collback함수에 대해 이해하는데 오랜시간이 걸렸다.
사실 아직도 잘 모르는것 같아
수업을 하면서 colback함수가 쓰이면 조금더 집중하고, 새로 알게 된 내용이 있으면 정리하면서 내것으로 만드는 시간이 필요할거 같다 !
🐾참조
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Promise
'프론트엔드 > Codestates' 카테고리의 다른 글
| [기술 면접 준비] 일반적으로 CSS를 불러오기 위해 <link>요소를 <head>요소의 자식 요소로 하고, javascript를 불러오기 위해 <script>요소를 <body>요소 끝나기 직전에 위치시키는 이유가 무엇인가요? (0) | 2022.09.27 |
|---|---|
| [Javascript] Node.js 모듈 (0) | 2022.09.27 |
| [Javascript] 프로토타입 체인 (0) | 2022.09.22 |
| [Javascript] 프로토타입과 클래스 (1) | 2022.09.21 |
| [Javascript] 객체 지향 프로그래밍 (1) | 2022.09.21 |