연쇄 약속은 JavaScript에서 비동기 작업을 관리하는 강력한 기술입니다. 이를 통해 한 약속의 출력이 다음에 공급되는 여러 비동기 작업을 시퀀싱 할 수 있습니다. 이것은 주로 .then()
메소드를 사용하여 달성됩니다. 각 .then()
호출은 인수로 기능을 취합니다. 이 기능은 이전 약속의 해결 된 값을 받고 새로운 약속을 반환합니다 (또는 암시 적으로 해결 된 약속이됩니다).
예를 들어 설명합니다. API에서 사용자 데이터를 가져오고 사용자 ID를 기반으로 게시물을 가져오고 페이지에 게시물을 표시하는 것을 상상해 보겠습니다.
<code class="javascript">fetchUserData() .then(userData => { // Process user data, extract userId const userId = userData.id; return fetchUserPosts(userId); // Returns a new promise }) .then(userPosts => { // Process user posts and display them displayPosts(userPosts); }) .catch(error => { // Handle any errors that occurred during the chain console.error("An error occurred:", error); }); //Example helper functions (replace with your actual API calls) function fetchUserData() { return new Promise((resolve, reject) => { setTimeout(() => { resolve({id: 123, name: "John Doe"}); }, 500); }); } function fetchUserPosts(userId) { return new Promise((resolve, reject) => { setTimeout(() => { resolve([{title: "Post 1"}, {title: "Post 2"}]); }, 500); }); } function displayPosts(posts) { console.log("User Posts:", posts); }</code>
이 코드는 먼저 사용자 데이터를 가져옵니다. 결과는 두 번째 .then()
블록으로 전달되어 사용자의 게시물을 가져옵니다. 마지막으로 게시물이 표시됩니다. .catch()
블록은 이러한 단계 중에 발생할 수있는 오류를 처리합니다. 이것은 기본 체인을 보여줍니다. 임의로 많은 비동기 작업을 포함하도록 이것을 확장 할 수 있습니다. async/await
(나중에 논의)는보다 복잡한 체인에 대한보다 읽기 쉬운 대안을 제공합니다.
약속 체인의 효과적인 오류 처리는 강력한 응용 프로그램에 중요합니다. 체인 끝에있는 단일 .catch()
체인의 어느 부분에서나 오류를 포착합니다. 그러나이 접근 방식은 오류의 정확한 소스를 정확히 찾아 내지 않기 때문에 디버깅을 어렵게 만들 수 있습니다.
더 나은 실습은 각 단계에서 오류를 처리하는 것입니다.
<code class="javascript">fetchUserData() .then(userData => { // Process user data, extract userId const userId = userData.id; return fetchUserPosts(userId); }) .then(userPosts => { // Process user posts and display them displayPosts(userPosts); }) .catch(error => { console.error("Error in fetching user data or posts:", error); }); function fetchUserData() { return new Promise((resolve, reject) => { setTimeout(() => { // Simulate an error reject(new Error("Failed to fetch user data")); }, 500); }); } // ... rest of the code remains the same</code>
또는 각 .then()
내에서 try...catch
Block을 사용하여 특정 오류를 처리 할 수 있습니다.
<code class="javascript">fetchUserData() .then(userData => { try { const userId = userData.id; return fetchUserPosts(userId); } catch (error) { console.error("Error processing user data:", error); //Optionally re-throw the error to be caught by the final catch throw error; } }) // ...rest of the chain</code>
이는보다 세분화 된 오류 처리와 더 나은 디버깅 기능을 제공합니다. 문제의 소스를 정확히 찾아내는 데 도움이되는 유익한 오류 메시지를 항상 제공하십시오.
길고 깊이 중첩 된 약속 체인은 읽고 유지하기가 어려워 질 수 있습니다. 몇 가지 전략은 가독성을 향상시킬 수 있습니다.
async/await
: async/await
약속으로 작업하기위한 클리너 구문을 제공하여 코드를 동기식과 쉽게 읽을 수 있도록합니다. 깊이 중첩 된 .then()
호출과 관련된 Doom의 피라미드를 피합니다.<code class="javascript">async function fetchDataAndDisplay() { try { const userData = await fetchUserData(); const userId = userData.id; const userPosts = await fetchUserPosts(userId); displayPosts(userPosts); } catch (error) { console.error("An error occurred:", error); } } fetchDataAndDisplay();</code>
.catch()
사용하여 항상 잠재적 오류를 처리하거나 try...catch
. 처리되지 않은 오류는 응용 프로그램 충돌 또는 예기치 않은 동작으로 이어질 수 있습니다.async/await
거나 체인을 더 작고 집중된 기능으로 분해하여이를 완화하십시오..then()
호출의 불필요한 중첩을 피하십시오. async/await
사용하여 코드를 단순화하고 가독성을 향상시킵니다..then()
블록 내의 각 기능은 체인을 올바르게 계속하기 위해 약속 (또는 약속으로 해결되는 가치)을 반환 해야합니다 . 그렇지 않으면 체인이 파손됩니다.finally
사용하지 않음 : .finally()
메소드는 약속이 해결되는지 거부하는지 여부에 관계없이 자원을 정리하는 데 유용합니다. 예를 들어, 데이터베이스 연결 또는 네트워크 스트림을 닫습니다.이러한 일반적인 함정을 피하고 위에서 설명한 모범 사례를 사용함으로써 JavaScript 약속을 사용하여 강력하고 유지 관리 가능하며 읽기 쉬운 비동기 워크 플로를 만들 수 있습니다.
위 내용은 복잡한 비동기 워크 플로우를 만들기 위해 약속을 어떻게 연쇄합니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!