async & await

1. async & await

  • es8에서 도입되었습니다.
  • 비동기 함수를 선언합니다.

2. 즉시 실행함수(Immediately invoked function expression, IIFE)

**(**function () {
	// 내용
}**)()**;

(() => {
	// 내용
})();
  • 외부 함수 없이 바로 await를 쓰고 싶을 때 아래처럼 활용합니다.
(async function() {
	// 내용
})();

(async () => {
	// 내용
})();

3. 예외 처리

(async () => {
	**try {**
	  let productResponse = await fetch('<https://api.test.com/proudcts>');
	  let firstProductId = productResponse.products[0].id;

	  let commentResponse = await fetch('<https://api.test.com/proudct/comments?id='+firstProductId>);
		let firstCommentId = commentResponse.comments[0].id;

	  let likeResponse = await fetch('<https://api.test.com/proudct/comment/likes?id='+firstCommentId>);
		let likesCount = likeResponse.likes.length;
	**} catch(error) {**
		console.log(error);
	**}**
})();
  • try와 catch

이벤트 루프

1. 이벤트 루프

Untitled
  • Heap
    • 단순히 메모리 영역을 지칭하는 용어입니다.
    • 변수 등의 정보를 저장합니다.
    • 콜스택 최상단에 있는 실행 컨텍스트가 실행되면서 참조되는 객체들이 저장되어 있는 메모리 공간입니다.
  • Call Stack
    • 실행하는 코드를 순서대로 실행하는 곳입니다.
    • 실행 컨텍스트가 추가되거나 제거됩니다.
    • 실행순서를 관리합니다.
  • Callback Queue
    • 처리할 메시지의 대기열입니다.
    • 비동기 함수의 콜백함수가 일시적으로 대기합니다.
    • 이벤트 핸들러가 일시적으로 대기합니다.

2. Call Stack

// main

function task(message) {
    // emulate time consuming task
    let n = 10000000000;
    while (n > 0){
        n--;
    }
    console.log(message);
}

console.log('Start script...');
task('Call an API');
console.log('Done!');
Untitled
https://www.javascripttutorial.net/javascript-event-loop/

3. 이벤트 루프의 작동

function greet() {
	console.log("Hello!");
}

function respond() {
	return setTimeout(() => {
		console.log("Hey!");
	}, 1000);
}

greet();
respond();
https://dev.to/lydiahallie/javascript-visualized-event-loop-3dif
  1. greet 호출
  2. respond 호출
  3. setTimeout 호출
  4. setTimeout의 콜백을 1초 뒤 콜백큐로 전달
  5. 콜스택이 비어있을 때 콜백큐에 있던 대기 작업이 하나씩 전달
  6. 콜백 실행
Last modified: 2022년 02월 17일

Comments

Write a Reply or Comment

Your email address will not be published.