개발자/그냥 js

Promise란

YoungDogg 2022. 1. 12. 21:41

 

promise란 (Producing Code)시간 좀 걸리는 코드와 (Consuming Code)반드시 기다려야 하는 코드를 연결하는 객체다.

 

객체 특징

properties.state (상태) peding fulfilled rejected
properties.result (결과) undefined a result value an error object

 

예제 1. 기본형이다.

const myResolve = () => {console.log("I'm myResolve")}
const myReject = () => {console.log("I'm myReject")}

let myPromise = new Promise(function(myResolve, myReject) {
// "Producing Code" (시간이 좀 걸린다)

  myResolve(); // 성공하면
  myReject();  // 에러뜨면
});

// "Consuming Code" (반드시 기다려야 하는 코드)
myPromise.then(
  function(value) { /* code if successful */  console.log("done")},
  function(error) { /* code if some error */ console.log("fail") }
);

예제 2. 기본형에 조건문을 추가했다.

예제 3. 타이머를 줘서 작동 원리를 본다, myResolve(성공했을 때), myReject(실패했을 때)는 콜백함수다.

 

3초가 지나면 myResolve의 인자값을 가져온다.

 

 

 

 

 


참고 링크

JavaScript Promises (w3schools.com)

 

JavaScript Promises

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com

Promise - JavaScript | MDN (mozilla.org)

 

Promise - JavaScript | MDN

The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.

developer.mozilla.org