본문 바로가기

[IT/Programming]/HTML related

Javascript (자바스크립트): async 와 await

반응형
# Javascript (자바스크립트): async 와 await 우선 단어 뜻부터. asynchronous: 동시에 일어나지 않는, 비동시적인, 비동기의. await: 기다리고 있다. 보통 javascript code 는 동시 다발적으로 (synchronous 하게) 실행되는데, 즉 코드가 적힌 순서대로 처리하는게 아니라 HTTP 요청을 보냈다가 숫자들 계산했다가 HTTP 답변이 왔으면 계산하다가 멈추고 HTTP 답변받은걸 처리했다가 문자열 띄우기도 했다가 alert 보냈다가 하는 식으로 말이다. 그렇기에 순서적으로 실행되어야 제대로 동작하는 코드가 있으면, 즉 HTTP 요청 ($.ajax, fetch 등) 후 데이터를 받아서 그 받은 데이터 가지고 화면에 표시해야 하는 작업이 있으면 그냥 javascript code 를 써서는 안된다. Callback function 으로 해결하던지 async/await 를 써야한다. ## PH
  • 2023-05-18: First posting.
## TOC ## Syntax (기본 문법) ``` async function 함수명() { await 비동기_처리_메서드(); // 꼭 Promise 객체를 반환해야 await 가 의도한 대로 동작. } 함수명(); // 실행. ```/ ``` async function logName() { let user=await fetchUser('domain.com/users/1'); // Promise 를 반환함. if (user.id===1) { console.log(user.name); } } logName(); // 실행. ```/ ``` function fetchItems() { return new Promise(function (resolve, reject) { let items=[1,2,3]; resolve(items); // resolve 하는 object 를 반환. }); } async function logItems() { let resultItems=await fetchItems(); // items 가 반환됨. console.log(resultItems); // [1,2,3] } logItems(); // 실행. ```/ ``` // HTTP 통신 동작을 모방한 코드 function fetchItems() { return new Promise(function (resolve, reject) { setTimeout(function () { let items = [1,2,3]; resolve(items); // resolve 하는 object 를 반환. }, 3000); }); } async function logItems() { let resultItems=await fetchItems(); // resolve 가 호출될때까지 기다렸다가 items 가 반환됨. console.log(resultItems); // [1,2,3] } logItems(); // 실행. ```/ ``` // jQuery ajax 코드 function fetchItems() { return new Promise(function (resolve, reject) { $.ajax('domain.com/items', function (response) { resolve(response); // resolve 하는 object 를 반환. }); }); } async function logItems() { let resultItems=await fetchItems(); // resolve 가 호출될때까지 기다렸다가 response 가 반환됨. console.log(resultItems); // [1,2,3] } logItems(); // 실행. ```/ ## async and await (feat. ChatGPT) In JavaScript, `async` and `await` are used to handle asynchronous operations in a more readable and synchronous-like manner. They are built on top of JavaScript's native Promise object and provide a way to write asynchronous code that resembles synchronous code flow. Here's an explanation of `async` and `await` with examples: ### Async Functions An `async` function is a function that implicitly returns a Promise and allows you to use the `await` keyword inside it. The `await` keyword can only be used inside an `async` function. ``` async function getData() { // Asynchronous operation const response = await fetch('https://api.example.com/data'); const data = await response.json(); return data; } getData(); // 실행. ```/ In the above example, the `getData()` function is declared as an `async` function. It performs an asynchronous operation by fetching data from an API and parsing the response as JSON. The `await` keyword is used to pause the function execution until the Promise resolves, and then it resumes and assigns the resolved value to the `response` and `data` variables. ### Await Expression The `await` keyword is used to pause the execution of an `async` function until the Promise resolves. It can only be used inside an `async` function. ``` async function fetchData() { const response = await fetch('https://api.example.com/data'); const data = await response.json(); console.log(data); } fetchData(); // 실행. ```/ In the above example, the `fetchData()` function uses `await` to pause execution until the Promise returned by `fetch()` resolves. Once the Promise resolves, the JSON data is obtained by calling `response.json()`. The `await` keyword ensures that the code execution waits for the Promise to be fulfilled before proceeding to the next line. ### Handling Errors Async functions also allow you to handle errors using traditional `try-catch` blocks. ``` async function fetchData() { try { const response = await fetch('https://api.example.com/data'); const data = await response.json(); console.log(data); } catch (error) { console.log('Error:', error); } } fetchData(); // 실행. ```/ In the above example, any errors that occur during the asynchronous operations are caught in the catch block, allowing you to handle and log the error appropriately. ### Parallel Execution Async functions also allow parallel execution of asynchronous operations using `Promise.all()`. ``` async function fetchData() { const promise1 = fetch('https://api.example.com/data1'); const promise2 = fetch('https://api.example.com/data2'); const [response1, response2] = await Promise.all([promise1, promise2]); const data1 = await response1.json(); const data2 = await response2.json(); console.log(data1, data2); } fetchData(); // 실행. ```/ In the above example, two API calls are made in parallel using `fetch()`, and their Promises are stored in `promise1` and `promise2`. `Promise.all()` is used to wait for both Promises to resolve, and then the responses are obtained. Finally, the JSON data is extracted from the responses using `response.json()`. By using `async` and `await`, you can write asynchronous JavaScript code in a more concise and readable manner, making it easier to handle promises and manage asynchronous operations. ## RRA
  1. javascript.info :: The JavaScript language \rightarrow Promises, async/await
  2. MDN :: async function, and MDN :: await
  3. joshua1988.github.io :: 자바스크립트 async와 await, 2019-07-30
  4. https://api.jquery.com/jquery.ajax/
  5. opentutorials.org :: jQuery Ajax, 2014-05-20
  6. kkh0977.tistory.com :: 14. (ajax/에이젝스) async await 및 promise 사용해 동기식 ajax 요청 실시, 2021-09-04
  7. araikuma.tistory.com :: [jQuery] Ajax 사용 - Ajax 메소드 \$.ajax() \$.get() .load(), 2018-12-04
반응형