async / wait는 promise에 비해 비동기 코드를 작성하는 새로운 방법입니다. async/await의 주요 장점은 향상된 가독성과 프라미스 체이닝을 방지하는 것입니다. Promise는 길어지고 읽기 어려울 수 있으며 디버그하기 어려울 수 있는 깊게 중첩된 콜백을 포함할 수 있습니다.
이전의 가져오기를 기억해 보세요.
fetch('https://jsonplaceholder.typicode.com/todos/1') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)) .finally(() => console.log('All done'));
async/await를 사용하면 코드를 다음과 같이 리팩터링할 수 있습니다.
async function fetchData() { try { const response = await fetch('https://jsonplaceholder.typicode.com/todos/1'); const data = await response.json(); console.log(data); } catch (error) { console.error('Error:', error); } finally { console.log('All done'); } } fetchData();
코드가 몇 줄 더 필요할 수 있지만 이 버전은 일반 동기 함수와 유사하기 때문에 읽기가 더 쉽습니다. 또한 .then() 문 내부의 함수가 더 복잡하면 가독성과 디버깅 가능성이 훨씬 더 큰 영향을 받습니다. async/await 예제가 훨씬 더 명확합니다.
비동기/대기 함수에는 비동기와 대기라는 두 가지 필수 부분이 있습니다. async 키워드는 함수 선언 앞에 추가되며, 비동기 작업이 시작될 때 wait가 사용됩니다.
레스토랑에서 음식을 주문하는 예를 들어 설명해 보겠습니다.
// Simulate the order process with async/await async function foodOrder() { console.log("Ordering food..."); await new Promise(resolve => setTimeout(resolve, 2000)); // Wait 2 seconds for food to be prepared return "Your food is ready!"; } // Simulate the eating process function eatFood(order) { console.log(order); // This logs "Your food is ready!" console.log("Enjoying the meal!"); } // Simulate continuing the conversation function continueConversation() { console.log("While waiting, you continue chatting with friends..."); } async function orderFood() { console.log("You've arrived at the restaurant."); const order = await foodOrder(); // Place the order and wait for it to be ready continueConversation(); // Chat while waiting eatFood(order); // Eat the food once it arrives } orderFood();
출력은 다음과 같습니다.
You've arrived at the restaurant. Ordering food... While waiting, you continue chatting with friends... Your food is ready! Enjoying the meal!
부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.
Copyright© 2022 湘ICP备2022001581号-3