자바스크립트: 약속 전체 가이드
약속이란 무엇입니까?
Promise는 비동기 프로그래밍을 위한 새로운 솔루션입니다. ES6는 이를 언어 표준에 통합하여 사용법을 통일하고 Promise 객체를 기본적으로 제공합니다.
이 도입으로 비동기 프로그래밍의 곤경이 크게 개선되어 콜백 지옥을 피할 수 있었습니다. 콜백 함수 및 이벤트와 같은 기존 솔루션보다 더 합리적이고 강력합니다.
간단히 말해서 Promise는 미래에 완료될 이벤트(일반적으로 비동기 작업)의 결과를 보유하는 생성자입니다. 구문론적으로 Promise는 비동기 작업 메시지를 검색할 수 있는 객체입니다. Promise는 다양한 비동기 작업을 동일한 방식으로 처리할 수 있는 통합 API를 제공합니다.
왜 Promise를 사용해야 할까요?
ES5의 콜백 지옥 문제를 효과적으로 해결할 수 있습니다(깊게 중첩된 콜백 함수 방지).
간결한 구문, 강력한 가독성, 유지 관리성을 갖춘 통일된 표준을 따릅니다.
Promise 객체는 간단한 API를 제공하여 비동기 작업을 보다 편리하고 유연하게 관리할 수 있습니다.
Promise의 상태
Promise를 사용할 때 세 가지 상태로 분류할 수 있습니다.
보류 중: 보류 중. Promise가 이행되거나 거부되지 않은 초기 상태입니다.
이행됨: 이행됨/해결됨/성공. Resolve()가 실행되면 Promise는 즉시 이 상태로 전환되어 해결되었으며 작업이 성공적으로 완료되었음을 나타냅니다.
거부됨: 거부됨/실패함. Reject()가 실행되면 Promise는 즉시 이 상태로 전환되어 거부되었으며 작업이 실패했음을 나타냅니다.
new Promise()가 실행되면 Promise 객체의 상태가 초기 상태인 보류 중으로 초기화됩니다. new Promise() 줄의 괄호 안 내용은 동기적으로 실행됩니다. 괄호 안에 해결 및 거부라는 두 가지 매개 변수가 있는 비동기 작업에 대한 함수를 정의할 수 있습니다. 예:
// Create a new promise const promise = new Promise((resolve, reject) => { //promise's state is pending as soon as entering the function console.log('Synchronous Operations'); //Begin to execute asynchronous operations if (Success) { console.log('success'); // If successful, execute resolve() to switch the promise's state to Fulfilled resolve(Success); } else { // If failed, excecute reject() to pass the error and switch the state to Rejected reject(Failure); } }); console.log('LukeW'); //Execute promise's then():to manage success and failure situations promise.then( successValue => { // Process promise's fulfilled state console.log(successValue, 'successfully callback'); // The successMsg here is the Success in resolve(Success) }, errorMsg => { //Process promise's rejected state console.log(errorMsg, 'rejected'); // The errorMsg here is the Failure in reject(Failure) } );
약속의 기본 사용법
새로운 Promise 객체 생성
Promise 생성자는 함수를 매개변수로 사용하며 이 함수에는 해결 및 거부라는 두 가지 인수가 있습니다.
const promise = new Promise((resolve, reject) => { // ... some code if (/* Success */){ resolve(value); } else { reject(error); } });
약속.해결
Promise.resolve(value)의 반환 값은 .then 호출과 연결될 수 있는 Promise 개체이기도 합니다. 코드는 다음과 같습니다.
Promise.resolve(11).then(function(value){ console.log(value); // print 11 });
resolve(11) 코드에서는 Promise 객체가 확인된 상태로 전환되어 인수 11을 후속 .then에 지정된 onFulfilled 함수에 전달합니다. Promise 객체는 새로운 Promise 구문을 사용하거나 Promise.resolve(value)를 사용하여 생성할 수 있습니다.
약속.거부
function testPromise(ready) { return new Promise(function(resolve,reject){ if(ready) { resolve("hello world"); }else { reject("No thanks"); } }); }; testPromise(true).then(function(msg){ console.log(msg); },function(error){ console.log(error); });
위 코드의 의미는 Promise 객체를 반환하는 testPromise 메서드에 인수를 전달하는 것입니다. 인수가 true이면 promise 개체의 해결() 메서드가 호출되고 여기에 전달된 매개 변수가 후속 .then의 첫 번째 함수에 전달되어 "hello world"가 출력됩니다. 인수가 false인 경우 Promise 객체의 Reject() 메서드가 호출되어 .then의 두 번째 함수가 트리거되고 "No thanks"가 출력됩니다.
약속된 방법
그 다음에()
then 메소드는 두 개의 콜백 함수를 매개변수로 받아들일 수 있습니다. 첫 번째 콜백 함수는 Promise 객체의 상태가 해결됨으로 변경될 때 호출되고, 두 번째 콜백 함수는 Promise 객체의 상태가 거부됨으로 변경될 때 호출됩니다. 두 번째 매개변수는 선택사항이므로 생략 가능합니다.
then 메소드는 새 Promise 인스턴스(원래 Promise 인스턴스가 아님)를 반환합니다. 따라서 첫 번째 메소드 이후에 다른 then 메소드가 호출되는 체인 구문을 사용할 수 있습니다.
비동기 이벤트를 순차적으로 작성해야 하는 경우(연속 실행이 필요함) 다음과 같이 작성할 수 있습니다.
let promise = new Promise((resolve,reject)=>{ ajax('first').success(function(res){ resolve(res); }) }) promise.then(res=>{ return new Promise((resovle,reject)=>{ ajax('second').success(function(res){ resolve(res) }) }) }).then(res=>{ return new Promise((resovle,reject)=>{ ajax('second').success(function(res){ resolve(res) }) }) }).then(res=>{ })
잡다()
Promise 객체에는 then 메소드 외에도 catch 메소드가 있습니다. 이 메소드는 거부를 위한 콜백 함수를 가리키는 then 메소드의 두 번째 매개변수와 동일합니다. 그러나 catch 메서드에는 추가 기능이 있습니다. 해결 콜백 함수를 실행하는 동안 오류가 발생하거나 예외가 발생하더라도 실행을 중지하지 않습니다. 대신 catch 메소드로 들어갑니다.
p.then((data) => { console.log('resolved',data); },(err) => { console.log('rejected',err); } ); p.then((data) => { console.log('resolved',data); }).catch((err) => { console.log('rejected',err); });
all()
The all method can be used to complete parallel tasks. It takes an array as an argument, where each item in the array is a Promise object. When all the Promises in the array have reached the resolved state, the state of the all method will also become resolved. However, if even one of the Promises changes to rejected, the state of the all method will become rejected.
let promise1 = new Promise((resolve,reject)=>{ setTimeout(()=>{ resolve(1); },2000) }); let promise2 = new Promise((resolve,reject)=>{ setTimeout(()=>{ resolve(2); },1000) }); let promise3 = new Promise((resolve,reject)=>{ setTimeout(()=>{ resolve(3); },3000) }); Promise.all([promise1,promise2,promise3]).then(res=>{ console.log(res); //result:[1,2,3] })
When the all method is called and successfully resolves, the result passed to the callback function is also an array. This array stores the values from each Promise object when their respective resolve functions were executed, in the order they were passed to the all method.
race()
The race method, like all, accepts an array where each item is a Promise. However, unlike all, when the first Promise in the array completes, race immediately returns the value of that Promise. If the first Promise's state becomes resolved, the race method's state will also become resolved; conversely, if the first Promise becomes rejected, the race method's state will become rejected.
let promise1 = new Promise((resolve,reject)=>{ setTimeout(()=>{ reject(1); },2000) }); let promise2 = new Promise((resolve,reject)=>{ setTimeout(()=>{ resolve(2); },1000) }); let promise3 = new Promise((resolve,reject)=>{ setTimeout(()=>{ resolve(3); },3000) }); Promise.race([promise1,promise2,promise3]).then(res=>{ console.log(res); //result:2 },rej=>{ console.log(rej)}; )
So, what is the practical use of the race method? When you want to do something, but if it takes too long, you want to stop it; this method can be used to solve that problem:
Promise.race([promise1,timeOutPromise(5000)]).then(res=>{})
finally()
The finally method is used to specify an operation that will be executed regardless of the final state of the Promise object. This method was introduced in the ES2018 standard.
promise .then(result => {···}) .catch(error => {···}) .finally(() => {···});
In the code above, regardless of the final state of the promise, after the then or catch callbacks have been executed, the callback function specified by the finally method will be executed.
What exactly does Promise solve?
In work, you often encounter a requirement like this: for example, after sending an A request using AJAX, you need to pass the obtained data to a B request if the first request is successful; you would need to write the code as follows:
let fs = require('fs') fs.readFile('./a.txt','utf8',function(err,data){ fs.readFile(data,'utf8',function(err,data){ fs.readFile(data,'utf8',function(err,data){ console.log(data) }) }) })
The above code has the following drawbacks:
The latter request depends on the success of the previous request, where the data needs to be passed down, leading to multiple nested AJAX requests, making the code less intuitive.
Even if the two requests don't need to pass parameters between them, the latter request still needs to wait for the success of the former before executing the next step. In this case, you also need to write the code as shown above, which makes the code less intuitive.
After the introduction of Promises, the code becomes like this:
let fs = require('fs') function read(url){ return new Promise((resolve,reject)=>{ fs.readFile(url,'utf8',function(error,data){ error && reject(error) resolve(data) }) }) } read('./a.txt').then(data=>{ return read(data) }).then(data=>{ return read(data) }).then(data=>{ console.log(data) })
This way, the code becomes much more concise, solving the problem of callback hell.
위 내용은 자바스크립트: 약속 전체 가이드의 상세 내용입니다. 자세한 내용은 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)

Python은 부드러운 학습 곡선과 간결한 구문으로 초보자에게 더 적합합니다. JavaScript는 가파른 학습 곡선과 유연한 구문으로 프론트 엔드 개발에 적합합니다. 1. Python Syntax는 직관적이며 데이터 과학 및 백엔드 개발에 적합합니다. 2. JavaScript는 유연하며 프론트 엔드 및 서버 측 프로그래밍에서 널리 사용됩니다.

웹 개발에서 JavaScript의 주요 용도에는 클라이언트 상호 작용, 양식 검증 및 비동기 통신이 포함됩니다. 1) DOM 운영을 통한 동적 컨텐츠 업데이트 및 사용자 상호 작용; 2) 사용자가 사용자 경험을 향상시키기 위해 데이터를 제출하기 전에 클라이언트 확인이 수행됩니다. 3) 서버와의 진실한 통신은 Ajax 기술을 통해 달성됩니다.

실제 세계에서 JavaScript의 응용 프로그램에는 프론트 엔드 및 백엔드 개발이 포함됩니다. 1) DOM 운영 및 이벤트 처리와 관련된 TODO 목록 응용 프로그램을 구축하여 프론트 엔드 애플리케이션을 표시합니다. 2) Node.js를 통해 RESTFULAPI를 구축하고 Express를 통해 백엔드 응용 프로그램을 시연하십시오.

보다 효율적인 코드를 작성하고 성능 병목 현상 및 최적화 전략을 이해하는 데 도움이되기 때문에 JavaScript 엔진이 내부적으로 작동하는 방식을 이해하는 것은 개발자에게 중요합니다. 1) 엔진의 워크 플로에는 구문 분석, 컴파일 및 실행; 2) 실행 프로세스 중에 엔진은 인라인 캐시 및 숨겨진 클래스와 같은 동적 최적화를 수행합니다. 3) 모범 사례에는 글로벌 변수를 피하고 루프 최적화, Const 및 Lets 사용 및 과도한 폐쇄 사용을 피하는 것이 포함됩니다.

Python과 JavaScript는 커뮤니티, 라이브러리 및 리소스 측면에서 고유 한 장점과 단점이 있습니다. 1) Python 커뮤니티는 친절하고 초보자에게 적합하지만 프론트 엔드 개발 리소스는 JavaScript만큼 풍부하지 않습니다. 2) Python은 데이터 과학 및 기계 학습 라이브러리에서 강력하며 JavaScript는 프론트 엔드 개발 라이브러리 및 프레임 워크에서 더 좋습니다. 3) 둘 다 풍부한 학습 리소스를 가지고 있지만 Python은 공식 문서로 시작하는 데 적합하지만 JavaScript는 MDNWebDocs에서 더 좋습니다. 선택은 프로젝트 요구와 개인적인 이익을 기반으로해야합니다.

개발 환경에서 Python과 JavaScript의 선택이 모두 중요합니다. 1) Python의 개발 환경에는 Pycharm, Jupyternotebook 및 Anaconda가 포함되어 있으며 데이터 과학 및 빠른 프로토 타이핑에 적합합니다. 2) JavaScript의 개발 환경에는 Node.js, VScode 및 Webpack이 포함되어 있으며 프론트 엔드 및 백엔드 개발에 적합합니다. 프로젝트 요구에 따라 올바른 도구를 선택하면 개발 효율성과 프로젝트 성공률이 향상 될 수 있습니다.

C와 C는 주로 통역사와 JIT 컴파일러를 구현하는 데 사용되는 JavaScript 엔진에서 중요한 역할을합니다. 1) C는 JavaScript 소스 코드를 구문 분석하고 추상 구문 트리를 생성하는 데 사용됩니다. 2) C는 바이트 코드 생성 및 실행을 담당합니다. 3) C는 JIT 컴파일러를 구현하고 런타임에 핫스팟 코드를 최적화하고 컴파일하며 JavaScript의 실행 효율을 크게 향상시킵니다.

Python은 데이터 과학 및 자동화에 더 적합한 반면 JavaScript는 프론트 엔드 및 풀 스택 개발에 더 적합합니다. 1. Python은 데이터 처리 및 모델링을 위해 Numpy 및 Pandas와 같은 라이브러리를 사용하여 데이터 과학 및 기계 학습에서 잘 수행됩니다. 2. 파이썬은 간결하고 자동화 및 스크립팅이 효율적입니다. 3. JavaScript는 프론트 엔드 개발에 없어서는 안될 것이며 동적 웹 페이지 및 단일 페이지 응용 프로그램을 구축하는 데 사용됩니다. 4. JavaScript는 Node.js를 통해 백엔드 개발에 역할을하며 전체 스택 개발을 지원합니다.
