Koras02
Koras02코딩웹
Koras02
전체 방문자
오늘
어제
  • 분류 전체보기 (299)
    • 백엔드 (59)
      • nestjs (2)
      • Ruby (3)
      • PostgresQL (11)
      • MySQL (5)
      • Haskell (7)
      • Koa (3)
      • Java (3)
      • Python (5)
      • Rust (5)
      • MongoDB (2)
      • PHP (3)
      • Spring Boot (1)
      • redis (5)
      • deno (2)
    • 웹서버 (3)
      • nginx (1)
      • Apache (2)
      • Google Web Server (0)
    • 모바일개발 (5)
      • Figma (0)
      • React Native (2)
      • swift (0)
      • Flutter (3)
      • Kotlin (0)
    • 프론트 엔드 (158)
      • HTML (34)
      • CSS (7)
      • Javascript (35)
      • Angular (0)
      • Typescript (2)
      • React (58)
      • Vue (2)
      • GIT (6)
      • GraphQL (1)
      • Doker (4)
      • Go (8)
      • svelte (1)
      • gatsby (0)
    • etc. (47)
      • Notion (0)
      • TIL (24)
      • Algorithm (17)
      • Algorithm 개념 정리 (2)
      • Wiki (3)
      • Official document (1)
    • 웹개념 (12)
    • 변수정리 (1)
    • VSCode (2)
    • 포트폴리오 분석 (2)
      • React (2)
    • os (5)
      • 윈도우 (4)
      • Mac (0)
      • 가상머신 (0)
      • linux (1)
    • 응용프로그램언어 (2)
      • C (2)
      • C++ (0)
      • C# (0)
    • 블로그 운영관련 (1)

블로그 메뉴

  • 홈
  • 태그
  • 방명록
글쓰기

공지사항

  • [공지사항] 개발 이슈나 공식문서 업데이트 업로드 예정입니⋯

인기 글

태그

  • koa
  • 하스켈
  • React
  • Til
  • 데이터 타입
  • redis
  • html5
  • html
  • PostgreSQL
  • javascript
  • Java
  • go
  • mysql
  • 알고리즘
  • 프로그래머스
  • Haskell
  • CSS
  • 문자열
  • Rust
  • Flutter

티스토리

최근 댓글

최근 글

250x250
hELLO · Designed By 정상우.
Koras02

Koras02코딩웹

[Javascript] Promise란 ?
프론트 엔드/Javascript

[Javascript] Promise란 ?

2021. 10. 13. 00:27
728x90

이번시간에는 Javascript의 객체인 Promise에 대해 알아보겠습니다.

 

Promise란?

Promise(약속)이라는 뜻으로 내용이 실행은 되었지만 결과를 아직 반환하지 않은 객체를 뜻합니다.

반환되지 않은 상태에서 Then을 붙이면 결과가 반환되고 

실행이 완료되지 않았으면 완료가 된 이후 Then 내부에 함수가 실행됩니다.

 


  Resolve(성공후 리턴값) -> then으로 연결
  Reject(실패시 리턴값) -> catch로 연결
  Finally 부분은 무조건 실행
const condition = true;
const promise = new Promise((resolve, reject) => {
        if (condition) {
            resolve("성공");
        } else {
            reject('실패');
        }
    });

promise
  .then((msg) => {
     console.log(msg); // 성공시 (resolve)
 })
  .catch((error) => {
      console.log(error); // 실패시 (reject)
 })
   .finally(() =>  {
      console.log('always') // 끝나고 무조건 실행
 })

프로미스의 then을 연달아 사용 가능(프로미스 체이닝)

then 안에서 return한 값이 다음 then으로 넘어간다.

return 값이 Promise라면 resolve 후 넘어감

에러의 경우 catch로 이동

에러는 catch에서 한 번에 처리함

    promise
       .then((msg) => {
           return new Promise((resolve, reject) => {
               resolve(msg);
           });
       })
       .then((msg2) => {
           console.log(msg2);
           return new Promise((resolve, reject) => {
               resolve(msg2);
           });
       })
       .then((msg3) => {
           console.log(msg3);
       })
       .catch((error) => {
           console.log(error);
       })

 
    Promise.resolve(성공의 리턴값): 바로 resolve하는 프로미스
    Promise.reject(실패 리턴값): 바로 reject하는 프로미스 
 
// Promise.all 동시실행
const promise1 = Promise.resolve('성공1');
const promise2 = Promise.resolve("성공2");

Promise.all([promise1, promise2])
    .then((result) => {
        console.log(result); // ['성공1', '성공2']
    })
    .catch((error) => {
        console.error(error);
    })

Promise.all(배열): 여러 개의 프로미스를 동시 실행

하나라도 실패시 catch로 감

Promise.allSettled로 실패한 것만 추려낼 수 잇다.

 

 

async / await

async function의 도입

 

변수 = await 프로미스; 인 경우 Promise 가 resolve된 값이 변수에 저장 된다.

변수 await 값; 인 경우 그 값이 변수에 저장된다.

async function findAndSaveUser(Users) {
    let user = await Users.findOne({});
    user.name = 'jungho';
    user = await user.save();
    user = await Users.findOne({ gender: 'm' })

    // 생략 
    
} catch(error) {
   console.error(error);
}

에러 처리를 위해 try catch로 감싸주어야 한다.

각각 프로미스 에러 처리를 위해서는 각각을 try catch로 감싸야한다.

 

for await of

노드 10부터 지원

for await(변수 of 프로미스배열)

resolve된 프로미스가 변수에 담겨서 나온다.

await를 사용하기에 async 함수 안에서 작성해야한다.

const promise1 = Promise.resolve('성공1');
const promise2 = Promise.resolve('성공2');
(async () => {
  for await (promise of [promise1, promise2]) {
    console.log(promise);
  }
})();

 

참고 링크

  • 자바스크립트 Promise 정리 - JinWooHyun
 

자바스크립트 Promise 정리

내용이 실행은 되었지만 결과를 아직 반환하지 않은 객체Then을 붙이면 결과를 반환함실행이 완료되지 않았으면 완료된 후에Then 내부 함수가 실행됨Resolve(성공리턴값) -> then으로 연결Reject(실패

velog.io

 

'프론트 엔드 > Javascript' 카테고리의 다른 글

[javascript] 드림코딩 자바스크립트 1.콘솔에 출력 script async와 defer의 차이점 및 앞으로 자바스크립트 공부 방향 | 프론트엔드 개발자 입문  (0) 2021.12.22
[javascript] 함수형 프로그래밍 과 자바스크립트와 객체지향  (0) 2021.10.12
[javascript]비동기적 처리(Callback, Promise, Async-Await)  (0) 2021.10.09
    '프론트 엔드/Javascript' 카테고리의 다른 글
    • [javascript] 드림코딩 자바스크립트 2.데이터 타입, data types, let vs var, hoisting
    • [javascript] 드림코딩 자바스크립트 1.콘솔에 출력 script async와 defer의 차이점 및 앞으로 자바스크립트 공부 방향 | 프론트엔드 개발자 입문
    • [javascript] 함수형 프로그래밍 과 자바스크립트와 객체지향
    • [javascript]비동기적 처리(Callback, Promise, Async-Await)
    Koras02
    Koras02
    현재 사용중인 언어 - next-js,react,vue, typescript

    티스토리툴바