JavaScript로 약속 취소 익히기
작가: 로사리오 데 키아라✏️
자바스크립트에서 Promise는 비동기 작업을 처리하기 위한 강력한 도구로, 특히 UI 관련 이벤트에 유용합니다. 이는 즉시 사용할 수 없지만 향후 어느 시점에 해결될 값을 나타냅니다.
Promise를 사용하면 개발자가 API 호출, 사용자 상호 작용 또는 애니메이션과 같은 작업을 처리할 때 더 깔끔하고 관리하기 쉬운 코드를 작성할 수 있습니다(또는 허용해야 합니다). .then(), .catch() 및 .finally()와 같은 메서드를 사용하면 Promises를 통해 악명 높은 "콜백 지옥"을 피하면서 성공 및 오류 시나리오를 보다 직관적으로 처리할 수 있습니다.
이 글에서는 새로운 Promise와 Promise를 해결하는 두 개의 함수, 세 가지를 포함하는 객체를 반환하여 더 깔끔하고 간단한 코드를 작성할 수 있는 새로운(2024년 3월 Promise.withResolvers() 메서드를 사용합니다. 이는 최근 업데이트이므로 이 기사의 예제를 실행하려면 최신 Node 런타임(v>22)이 필요합니다.
기존 JavaScript Promise 메서드와 새로운 JavaScript Promise 메서드 비교
기능적으로 동일한 다음 두 코드 덩어리에서 Promise를 해결하거나 거부하는 메서드를 할당하는 기존 접근 방식과 새로운 접근 방식을 비교할 수 있습니다.
let resolve, reject; const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); Math.random() > 0.5 ? resolve("ok") : reject("not ok");
위 코드에서 Promise의 가장 전통적인 사용법을 볼 수 있습니다. 새 Promise 객체를 인스턴스화한 다음 생성자에서 두 가지 함수인 해결 및 거부를 할당해야 합니다. 필요합니다.
다음 코드 조각에서는 동일한 코드 덩어리가 새로운 Promise.withResolvers() 메서드를 사용하여 다시 작성되었으며 더 단순해 보입니다.
const { promise, resolve, reject } = Promise.withResolvers(); Math.random() > 0.5 ? resolve("ok") : reject("not ok");
여기서 새로운 접근 방식이 어떻게 작동하는지 확인할 수 있습니다. .then() 메서드와 두 함수인 해결 및 거부를 호출할 수 있는 Promise를 반환합니다.
Promise에 대한 기존 접근 방식은 단일 함수 내에서 생성 및 이벤트 처리 논리를 캡슐화합니다. 이는 여러 조건이나 코드의 다른 부분이 Promise를 해결하거나 거부해야 하는 경우 제한될 수 있습니다.
반대로 Promise.withResolvers()는 Promise 생성을 해결 논리에서 분리하여 더 큰 유연성을 제공하므로 복잡한 조건이나 여러 이벤트를 관리하는 데 적합합니다. 그러나 간단한 사용 사례의 경우 표준 약속 패턴에 익숙한 사용자에게는 기존 방법이 더 간단하고 친숙할 수 있습니다.
실제 예: API 호출
이제 보다 현실적인 예를 통해 새로운 접근 방식을 테스트할 수 있습니다. 아래 코드에서 API 호출의 간단한 예를 볼 수 있습니다.
function fetchData(url) { return new Promise((resolve, reject) => { fetch(url) .then(response => { // Check if the response is okay (status 200-299) if (response.ok) { return response.json(); // Parse JSON if response is okay } else { // Reject the promise if the response is not okay reject(new Error('API Invocation failed')); } }) .then(data => { // Resolve the promise with the data resolve(data); }) .catch(error => { // Catch and reject the promise if there is a network error reject(error); }); }); } // Example usage const apiURL = '<ADD HERE YOU API ENDPOINT>'; fetchData(apiURL) .then(data => { // Handle the resolved data console.log('Data received:', data); }) .catch(error => { // Handle any errors that occurred console.error('Error occurred:', error); });
fetchData 함수는 URL을 가져와서 fetch API를 사용하여 API 호출을 처리하는 Promise를 반환하도록 설계되었습니다. 응답 상태가 성공을 나타내는 200-299 범위 내에 있는지 확인하여 응답을 처리합니다.
성공하면 응답이 JSON으로 구문 분석되고 결과 데이터로 Promise가 해결됩니다. 응답이 성공하지 못하면 적절한 오류 메시지와 함께 Promise가 거부됩니다. 또한 이 함수에는 네트워크 오류를 포착하는 오류 처리가 포함되어 있으며, 그러한 오류가 발생하면 Promise를 거부합니다.
이 예에서는 이 함수를 사용하는 방법을 보여 주며, .then() 블록으로 해결된 데이터를 관리하고 .catch() 블록을 사용하여 오류를 처리하는 방법을 보여줌으로써 성공적인 데이터 검색과 오류가 모두 적절하게 관리되도록 보장합니다.
아래 코드에서는 새로운 Promise.withResolvers() 메서드를 사용하여 fetchData() 함수를 다시 작성했습니다.
function fetchData(url) { const { promise, resolve, reject } = Promise.withResolvers(); fetch(url) .then(response => { // Check if the response is okay (status 200-299) if (response.ok) { return response.json(); // Parse JSON if response is okay } else { // Reject the promise if the response is not okay reject(new Error('API Invocation failed')); } }) .then(data => { // Resolve the promise with the data resolve(data); }) .catch(error => { // Catch and reject the promise if there is a network error reject(error); }); return promise; }
보시다시피 위의 코드는 더 읽기 쉽고 Promise 객체의 역할은 명확합니다. fetchData 함수는 성공적으로 해결되거나 실패할 Promise를 반환하고 각 경우에 적절한 메소드를 호출합니다. . api.invocation.{old|new}.js라는 저장소에서 위의 코드를 찾을 수 있습니다.
약속 취소
다음 코드는 Promise 취소 메소드를 구현하는 방법을 탐색합니다. 아시다시피 JavaScript에서는 Promise를 취소할 수 없습니다. Promise는 비동기 작업의 결과를 나타내며, 생성된 후에는 취소할 수 있는 기본 제공 메커니즘 없이 해결 또는 거부하도록 설계되었습니다.
이 제한은 Promise에 정의된 상태 전환 프로세스가 있기 때문에 발생합니다. 보류 중으로 시작하고 일단 해결되면 상태를 변경할 수 없습니다. 작업 자체를 제어하기보다는 작업 결과를 캡슐화하기 위한 것입니다. 즉, 기본 프로세스에 영향을 주거나 취소할 수 없습니다. 이 디자인 선택은 약속을 단순하게 유지하고 작업의 최종 결과를 나타내는 데 중점을 둡니다.
const cancellablePromise = () => { const { promise, resolve, reject } = Promise.withResolvers(); promise.cancel = () => { reject("the promise got cancelled"); }; return promise; };
In the code above, you can see the object named cancellablePromise, which is a promise with an additional cancel() method that, as you can see, simply forces the invocation of the reject method. This is just syntactic sugar and does not cancel a JavaScript Promise, though it may help in writing clearer code.
An alternative approach is to use an AbortController and AbortSignal, which can be tied to the underlying operation (e.g., an HTTP request) to cancel it when needed. From the documentation, you can see that the AbortController and AbortSignal approach is a more expressive implementation of what we implemented in the code above: once the AbortSignal is invoked, the promise just gets rejected.
Another approach is to use reactive programming libraries like RxJS, which offers an implementation of the Observable pattern, a more sophisticated control over async data streams, including cancellation capabilities.
A comparison between Observables and Promises
When speaking about practical use cases, Promises are well-suited for handling single asynchronous operations, such as fetching data from an API. In contrast, Observables are ideal for managing streams of data, such as user input, WebSocket events, or HTTP responses, where multiple values may be emitted over time.
We already clarified that once initiated, Promises cannot be canceled, whereas Observables allow for cancellation by unsubscribing from the stream. The general idea is that, with Observables, you have an explicit structure of the possible interaction with the object:
- You create an Observable, and then all the Observables can subscribe to it
- The Observable carries out its work, changing state and emitting events. All the Observers will receive the updates – this is the main difference with Promises. A Promise can be resolved just once while the Observables can keep emitting events as long as there are Observers
- Once the Observer is not interested in the events from the Observables, it can unsubscribe, freeing resources
This is demonstrated in the code below:
import { Observable } from 'rxjs'; const observable = new Observable(subscriber => { subscriber.next(1); subscriber.next(2); subscriber.next(3); subscriber.complete(); }); const observer = observable.subscribe({ next(x) { console.log('Received value:', x); }, complete() { console.log('Observable completed'); } }); observer.unsubscribe();
This code cannot be rewritten with Promises because the Observable returns three values while a Promise can only be resolved once.
To experiment further with the unsubscribe method, we can add another Observer that will use the takeWhile() method: it will let the Observer wait for values to match a specific condition; in the code below, for example, it keeps receiving events from the Observable while the value is not 2:
import { Observable, takeWhile } from 'rxjs'; const observable = new Observable(subscriber => { subscriber.next(1); subscriber.next(2); subscriber.next(3); subscriber.complete(); }); const observer1 = observable.subscribe({ next(x) { console.log('Received by 1 value:', x); }, complete() { console.log('Observable 1 completed'); } }); const observer2 = observable.pipe( takeWhile(value => value != "2") ).subscribe(value => console.log('Received by 2 value:', value));
In the code above, observer1 is the same as we have already seen: it will just subscribe and keep receiving all the events from the Observable. The second one, observer2, will receive elements from the Observable while the condition is matched. In this case, this means when the value is different from 2.
From the execution, you can see how the two different mechanisms work:
$ node observable.mjs Received by 1 value: 1 Received by 1 value: 2 Received by 1 value: 3 Observable 1 completed Received by 2 value: 1 $
Conclusion
In this article, we investigated the new mechanism to allocate a Promise in JavaScript and laid out some of the possible ways to cancel a Promise before its completion. We also compared Promises with Observable objects, which not only offer the features of Promises but extend them by allowing multiple emissions of events and a proper mechanism for unsubscribing.
LogRocket: Debug JavaScript errors more easily by understanding the context
Debugging code is always a tedious task. But the more you understand your errors, the easier it is to fix them.
LogRocket allows you to understand these errors in new and unique ways. Our frontend monitoring solution tracks user engagement with your JavaScript frontends to give you the ability to see exactly what the user did that led to an error.
LogRocket records console logs, page load times, stack traces, slow network requests/responses with headers + bodies, browser metadata, and custom logs. Understanding the impact of your JavaScript code will never be easier!
Try it for free.
위 내용은 JavaScript로 약속 취소 익히기의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











프론트 엔드 개발시 프론트 엔드 열지대 티켓 인쇄를위한 자주 묻는 질문과 솔루션, 티켓 인쇄는 일반적인 요구 사항입니다. 그러나 많은 개발자들이 구현하고 있습니다 ...

JavaScript는 현대 웹 개발의 초석이며 주요 기능에는 이벤트 중심 프로그래밍, 동적 컨텐츠 생성 및 비동기 프로그래밍이 포함됩니다. 1) 이벤트 중심 프로그래밍을 사용하면 사용자 작업에 따라 웹 페이지가 동적으로 변경 될 수 있습니다. 2) 동적 컨텐츠 생성을 사용하면 조건에 따라 페이지 컨텐츠를 조정할 수 있습니다. 3) 비동기 프로그래밍은 사용자 인터페이스가 차단되지 않도록합니다. JavaScript는 웹 상호 작용, 단일 페이지 응용 프로그램 및 서버 측 개발에 널리 사용되며 사용자 경험 및 크로스 플랫폼 개발의 유연성을 크게 향상시킵니다.

기술 및 산업 요구에 따라 Python 및 JavaScript 개발자에 대한 절대 급여는 없습니다. 1. 파이썬은 데이터 과학 및 기계 학습에서 더 많은 비용을 지불 할 수 있습니다. 2. JavaScript는 프론트 엔드 및 풀 스택 개발에 큰 수요가 있으며 급여도 상당합니다. 3. 영향 요인에는 경험, 지리적 위치, 회사 규모 및 특정 기술이 포함됩니다.

JavaScript를 배우는 것은 어렵지 않지만 어려운 일입니다. 1) 변수, 데이터 유형, 기능 등과 같은 기본 개념을 이해합니다. 2) 마스터 비동기 프로그래밍 및 이벤트 루프를 통해이를 구현하십시오. 3) DOM 운영을 사용하고 비동기 요청을 처리합니다. 4) 일반적인 실수를 피하고 디버깅 기술을 사용하십시오. 5) 성능을 최적화하고 모범 사례를 따르십시오.

JavaScript의 최신 트렌드에는 Typescript의 Rise, 현대 프레임 워크 및 라이브러리의 인기 및 WebAssembly의 적용이 포함됩니다. 향후 전망은보다 강력한 유형 시스템, 서버 측 JavaScript 개발, 인공 지능 및 기계 학습의 확장, IoT 및 Edge 컴퓨팅의 잠재력을 포함합니다.

동일한 ID로 배열 요소를 JavaScript의 하나의 객체로 병합하는 방법은 무엇입니까? 데이터를 처리 할 때 종종 동일한 ID를 가질 필요가 있습니다 ...

이 기사에서 시차 스크롤 및 요소 애니메이션 효과 실현에 대한 토론은 Shiseido 공식 웹 사이트 (https://www.shiseido.co.jp/sb/wonderland/)와 유사하게 달성하는 방법을 살펴볼 것입니다.

Console.log 출력의 차이의 근본 원인에 대한 심층적 인 논의. 이 기사에서는 Console.log 함수의 출력 결과의 차이점을 코드에서 분석하고 그에 따른 이유를 설명합니다. � ...
