Promises

서정준·2022년 4월 13일
0

ES6

목록 보기
2/7
post-thumbnail
post-custom-banner

Promise

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

  • Promise는 현재에는 당장 얻을 수는 없지만 가까운 미래에는 얻을 수 있는 어떤 데이터에 접근하기 위한 방법을 제공합니다. 당장 원하는 데이터를 얻을 수 없다는 것은 데이터를 얻는데까지 지연 시간(delay, latency)이 발생하는 경우를 말합니다.

※ synchronous(동기) vs asynchronous(비동기)

https://velog.io/@lsj8367/Javascript-%EB%8F%99%EA%B8%B0%EC%99%80-%EB%B9%84%EB%8F%99%EA%B8%B0%EB%B0%A9%EC%8B%9D%EC%9D%98-%EC%B0%A8%EC%9D%B4%EC%A0%90

Using Promises

The then() method returns a Promise. It takes up to two arguments: callback functions for the success and failure cases of the Promise.

The catch() method returns a Promise and deals with rejected cases only.

  • then과 catch의 함수가 동시에 호출됨.(순차적으로 호출 되는 것이 아님.)
const amISexy = new Promise((resolve, reject) => {
  setTimeout(reject, 3000, "you are ugly");
})

amISexy
  .then(result => console.log(result))
  .catch(error => console.log(error)) // you are ugly

Chaining Promises

Each .then() returns a newly generated promise object, which can optionally be used for chaining;

const amISexy = new Promise((resolve, reject) => {
  resolve(2);
})

const timesTwo = number => number * 2;
amISexy
  .then(timesTwo)
  .then(timesTwo)
  .then(timesTwo)
  .then(timesTwo)
  .then(timesTwo)
  .then(timesTwo)
  .then(lastNumber => console.log(lastNumber)) // 128

error를 고의적으로 생성한 후 결과 (아래의 그림과 같은 error 발생.)

const amISexy = new Promise((resolve, reject) => {
  resolve(2);
})

const timesTwo = number => number * 2;
amISexy
  .then(timesTwo)
  .then(timesTwo)
  .then(timesTwo)
  .then(timesTwo)
  .then(timesTwo)
  .then(() => {
  throw Error("something is wrong")
})
  .then(lastNumber => console.log(lastNumber))

promise.all

Wait for all promises to be resolved, or for any to be rejected.

const p1 = new Promise(resolve => {
  setTimeout(resolve, 5000, "First");
});

const p2 = new Promise(resolve => {
  setTimeout(resolve, 3000, "second");
});

const p3 = new Promise(resolve => {
  setTimeout(resolve, 1000, "third");
});

// p1은 5초 p2는 3초 p1은 1초에 값이 나오지만 promise.all을 했을 경우 모든 작업이 끝난 후 값을 출력한다.
const motherPromise = Promise.all([p1,p2,p3])

motherPromise.then(values => console.log(values)) // ['First', 'second', 'third']
const p1 = new Promise(resolve => {
  setTimeout(resolve, 5000, "First");
});

const p2 = new Promise((resolve, reject) => {
  setTimeout(reject, 3000, "I hate JS");
});

const p3 = new Promise(resolve => {
  setTimeout(resolve, 1000, "third");
});

const motherPromise = Promise.all([p1,p2,p3])

// 자식 promise에 error가 발생 했을 경우 자식 promise의 error값을 출력한다.
motherPromise
  .then(values => console.log(values))
  .catch(err => console.log(err)) // I hate JS

Promise.race

If the returned promise resolves, it is resolved with the value of the first promise in the iterable that resolved.
If it rejects, it is rejected with the reason from the first promise that was rejected.

const p1 = new Promise(resolve => {
  setTimeout(resolve, 5000, "First");
});

const p2 = new Promise(resolve => {
  setTimeout(resolve, 1000, "second");
});

const p3 = new Promise(resolve => {
  setTimeout(resolve, 3000, "third");
});

const motherPromise = Promise.race([p1,p2,p3])

motherPromise
  .then(values => console.log(values))
  .catch(err => console.log(err)) // second

finally

The finally() method returns a Promise. When the promise is finally either fulfilled or rejected

  • 로딩할 때 마지막으로 데이터를 보여 줄 때 사용.
const p1 = new Promise(resolve => {
  setTimeout(resolve, 5000, "First");
})
.then(value => console.log(value))
.catch(error => console.log(error))
.finally(() => console.log("I'm done")) // First I'm done

실제 사용 예시

  • API 호출시 사용.
fetch("https://yts.mx/api/v2/list_movies.json")
    .then((response) => {return response.json();})
    .then((potato) => console.log(potato))
    .catch((e) => console.log(`${e}`));

출처

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
https://www.daleseo.com/js-async-promise/

profile
통통통통
post-custom-banner

0개의 댓글