promise 코드

이태혁·2021년 1월 7일
0

🦊 Promise 만들기

const myPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('result');
  }, 1000)
})



myPromise
.then(result => {
  console.log(result)
})
.catch(e => {
  console.error(e)
}
const myPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    reject(new Error());
  }, 1000)
})



myPromise
.then(result => {
  console.log(result)
})
.catch(e => {
  console.error(e)
}

🦊 Promise 사용하기(then, catch)

function increaseAndPrint(n) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const value = n + 1;
      if (value === 3) {
        const error = new Error();
        error.name = 'ValueIsFiveError';
        reject(error);
        return;
      }
      console.log(value);
      resolve(value);
    }, 1000)
  })
}

increaseAndPrint(0)
.then(n => {
  return increaseAndPrint(n);
  }
)
.then(n => {
  return increaseAndPrint(n);
  }
)
.then(n => {
  return increaseAndPrint(n);
  }
)
.catch(e => {
  console.error(e);
})

위 아래는 같은 코드라고함
then에 자동으로 위에서 넘겨온 결과를 인자로 넣어주는듯

function increaseAndPrint(n) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const value = n + 1;
      if (value === 3) {
        const error = new Error();
        error.name = 'ValueIsFiveError';
        reject(error);
        return;
      }
      console.log(value);
      resolve(value);
    }, 1000)
  })
}


increaseAndPrint(0)
.then( increaseAndPrint)
.then( increaseAndPrint)
.then( increaseAndPrint)
.catch(e => {
  console.error(e);
}
profile
back-end, cloud, docker, web의 관심이 있는 예비개발자입니다.

0개의 댓글