자바스크립트: 약속 전체 가이드

WBOY
풀어 주다: 2024-08-26 21:36:02
원래의
215명이 탐색했습니다.

Javascript: Promise Complete Guide

약속이란 무엇입니까?

Promise는 비동기 프로그래밍을 위한 새로운 솔루션입니다. ES6는 이를 언어 표준에 통합하여 사용법을 통일하고 Promise 객체를 기본적으로 제공합니다.

이 도입으로 비동기 프로그래밍의 곤경이 크게 개선되어 콜백 지옥을 피할 수 있었습니다. 콜백 함수 및 이벤트와 같은 기존 솔루션보다 더 합리적이고 강력합니다.

간단히 말해서 Promise는 미래에 완료될 이벤트(일반적으로 비동기 작업)의 결과를 보유하는 생성자입니다. 구문론적으로 Promise는 비동기 작업 메시지를 검색할 수 있는 객체입니다. Promise는 다양한 비동기 작업을 동일한 방식으로 처리할 수 있는 통합 API를 제공합니다.

왜 Promise를 사용해야 할까요?

  • ES5의 콜백 지옥 문제를 효과적으로 해결할 수 있습니다(깊게 중첩된 콜백 함수 방지).

  • 간결한 구문, 강력한 가독성, 유지 관리성을 갖춘 통일된 표준을 따릅니다.

  • Promise 객체는 간단한 API를 제공하여 비동기 작업을 보다 편리하고 유연하게 관리할 수 있습니다.

Promise의 상태

Promise를 사용할 때 세 가지 상태로 분류할 수 있습니다.

  1. 보류 중: 보류 중. Promise가 이행되거나 거부되지 않은 초기 상태입니다.

  2. 이행됨: 이행됨/해결됨/성공. Resolve()가 실행되면 Promise는 즉시 이 상태로 전환되어 해결되었으며 작업이 성공적으로 완료되었음을 나타냅니다.

  3. 거부됨: 거부됨/실패함. 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!