상세 컨텐츠

본문 제목

ch8 Promises

노마드/ES6

by hippo0207 2022. 7. 22. 14:16

본문

0. Async

JS 비동기성 : 한꺼번에 여러가지를 실행 >> 순서대로 시작해도 끝나는순서가 다름 (앞에거 끝나길 기다려주지않음)

1. creating promises 

  • Promise 객체는 비동기 작업이 맞이할 미래의 완료 또는 실패와 그 결과 값을 나타냅니다.
const hello = amISexy = new Promise((resolve, reject)=> {});

console.log(amISexy);  >>> Promise {<pending>}

>> console.log 진행되고 위에 hello는 pending중이라고 함 >> resolve 함수를 실행해야 끝이남

  • 예제1
const hello = amISexy = new Promise((resolve, reject)=> { // promise만들고
    setTimeout(resolve, 3000, "yes you are"); // 3초후에 실행되고
});

console.log(amISexy);

//setTimeout(() => {
//    console.log(amISexy);
//}, 1000);  // 매초마다 console.log 실행
setInterval(console.log, 1000, amISexy);
--------------
Promise {<pending>}
Promise {<pending>}
Promise {<pending>}
Promise {<fulfilled>: 'yes you are'}
Promise {<fulfilled>: 'yes you are'}
Promise {<fulfilled>: 'yes you are'}
Promise {<fulfilled>: 'yes you are'}~~~~
  • 예제2
console.log(amISexy);
setTimeout(console.log, 1000, amISexy);
setTimeout(console.log, 2000, amISexy);
setTimeout(console.log, 3000, amISexy);
---------------
Promise {<pending>}
Promise {<pending>}
Promise {<pending>}
Promise {<fulfilled>: 'yes you are'}

2. using promise  >> .then 

const amISexy = new Promise((resolve, reject)=> { // promise만들고
    setTimeout(resolve, 3000, "yes you are"); // 3초후에 실행되고
    //resolve("Yes you are"); >> 바로실행
});

//amISexy.then(value => console.log(value));
const thenFn = value => console.log(value);
amISexy.then(thenFn);
  • reject될경우?
const amISexy = new Promise((resolve, reject)=> { // promise만들고
    setTimeout(reject, 3000, "yes you are"); // reject 일경우
    
});

amISexy
    .then(result => console.log(result)) // >> Uncaught (in promise) yes you are 
    //: Uncaught = catch 못잡았다는 뜻 (catch넣기 전임)
    .catch(error=> console.log(error)); //>> yes you are
    // then, catch : 각각 따로일어남. then일어나면 catch안일어남, 반대도 마찬가지

 

3. chaining promises

  • then >> chaining시  return 값 필수임 >> 다음then 에 넘겨줄거임
const amISexy = new Promise((resolve, reject)=> { 
    resolve(2);
});

<!--
amISexy
    .then(number => {
        console.log(number * 2);   // 4
        return number * 2;
    })
    .then(otherNumber => {
        console.log(otherNumber * 2);  // 8
    });
 -->
----------------->>
const timesTwo = (number) => number * 2;

amISexy
    .then(timesTwo)
    .then(timesTwo)
    .then(timesTwo)
    .then(timesTwo)
    .then(timesTwo)
    .then(lastNumber => console.log(lastNumber));  // >> 64
  • 에러가 발생할경우?
amISexy
    .then(timesTwo)
    .then(timesTwo)
    .then(timesTwo)
    .then(timesTwo)
    .then(timesTwo)
    .then(() => {
        throw Error("something");
    })
    .then(lastNumber => console.log(lastNumber))
    .catch(error => console.log(error));
    // >>> Error: something

4. promise.all

:  순회 가능한 객체에 주어진 모든 프로미스가 이행한 후, 혹은 프로미스가 주어지지 않았을 때 이행하는 Promise를 반환합니다

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.all([p1, p2, p3]);

motherPromise.then(values => console.log(values)); 
// >> (3) ['First', 'Second', 'Third']  // 5초걸림
// 각각의 끝나는순서는 상관없이, array순서대로 return
  • 주어진 프로미스 중 하나가 거부하는 경우, 첫 번째로 거절한 프로미스의 이유를 사용해 자신도 거부합니다.
const p1 = new Promise((resolve) => {
    setTimeout(resolve, 5000, "First");
});

const p2 = new Promise((resolve, reject) => {
    setTimeout(reject, 1000, "I hate JS");     //>>>>>>>>>reject일경우
});

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

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

motherPromise.then(values => console.log(values)); 
// forEs.html:1 Uncaught (in promise) I hate JS  >> 2초쯤 걸림
  • >> catch 추가 >> 
motherPromise
  .then((values) => console.log(values))
  .catch((err) => console.log(err)); // I hate JS

5. Promise.race

: 하나라도 resove or reject&catch 되면 됨 >> 먼저되는거만 나옴

  • >> 밑에꺼 시간바뀜
const p1 = new Promise((resolve) => {
  setTimeout(resolve, 10000, "First");
});

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

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));
      // >> Third
 --> 
 Promise.race([p1, p2, p3])
  .then((values) => console.log(values))
  .catch((err) => console.log(err));  // >> Third

6. Finally

const p1 = new Promise((resolve, reject) => {
  //setTimeout(resolve, 1000, "First");
  setTimeout(reject, 1000, "reject");
})
  .then((value) => console.log(value))
  .catch((e) => console.log(`${e}❌`))
  .finally(() => console.log("Im done")); 
  // 다 끝나고나서 실행됨
  // reject❌ Im done

7. Real world Promises

  • fetch : 뭔가를 가꼬옴
fetch("http://127.0.0.1:5500/forEs.html") // live server설치했음ㅎ
  .then((response) => console.log(response))
  .catch((e) => console.log(`❌${e}`));

>> body :: stream >> json으로 바꾸고싶음 (json있는 페이지라면 ㅇㅇ)

  • response 가 새로운 promise를 return >> then으로 받아주야함
fetch("http://127.0.0.1:5500/forEs.html")
  .then((response) => response.text())
  // response >> Promise return하는 함수내장됨
  .then((potato) => console.log(potato))
  .catch((e) => console.log(`❌${e}`));

response.text 라서 txt로 우루루나옴

https://yts.mx/api

 

Page not found (Error 404) - YTS YIFY

Download YIFY Movies Torrents - the only official YIFY website. Download all YTS YIFY movies torrents for free in 720p, 1080p, 4K and 3D quality. Smallest size with best quality and fast downloads at yts.torrentbay.to.

yts.torrentbay.to

>> json 받을만한 사이트임

https://velog.io/@geunwoobaek/CORS-%EC%9B%90%EC%9D%B8-%EB%B0%8F-%ED%95%B4%EA%B2%B0%EB%B0%A9%EB%B2%95

fetch("https://yts.mx/api/v2/list_movies.json")
  .then((response) => {
    console.log(response);
    return response.json();
  })
  .then((json) => console.log(json))
  .catch((e) => console.log(`❌${e}`));

 

'노마드 > ES6' 카테고리의 다른 글

ch10. classes  (0) 2022.07.23
ch.9 async/ await  (0) 2022.07.23
ch6~7. rest & spread & for of loop  (0) 2022.07.21
ch5. Destruction(비구조화)  (0) 2022.07.20
ch4. Array  (0) 2022.07.20

관련글 더보기

댓글 영역