javascript: Promise

Alpha, Orderly·2023년 6월 11일
0

typescript & javascript

목록 보기
5/6
정보 출처
https://www.youtube.com/watch?v=DHvZLI7Db8E - Javascript promise in 10 minutes

Promise

  • 비동기 작업을 처리하는 방법
  • Promise 객체는 생성자의 Argument로 하나의 함수를 받는다.
let p = new Promise((resolve, reject) => {
	let a = 1 + 1;
    if(a === 2) resolve('성공');
    else reject('실패');
});
// resolve에는 성공했을때 전달할 값, reject에는 실패했을때 전달할 값이 들어간다.

p
.then((message) => console.log(message))
.catch((message) => console.log(message))
// resolve를 통해 전달된 값은 then 블록의 message로 전달,
// reject를 통해 전달된 값은 catch 블록의 message로 전달. 

Promise.all

  • Promise 배열을 Argument로 받아 전부 resolve되면 결과를 배열로 리턴
  • 이중 하나라도 reject로 값을 전달되면 reject되어 catch로 그 결과를 리턴
  • Concurrent 하게 실행되나 Parallel 하진 않다.
    • 여러 Promise 가 완전히 동시에 실행되진 않는다.

Promise.resolve(promise)

  • Argument로 주어진 promise/값을 찾아 then()절로 보내거나 에러가 생기면 catch()로 보냄.
profile
만능 컴덕후 겸 번지 팬

0개의 댓글