[JS] Promise

강은비·2022λ…„ 1μ›” 3일
0

JS

λͺ©λ‘ 보기
9/19
post-thumbnail
post-custom-banner

πŸ“Œ Promiseλž€?

비동기 μž‘μ—…μ˜ μ΅œμ’… 성곡 λ˜λŠ” μ‹€νŒ¨λ₯Ό λ‚˜νƒ€λ‚΄λŠ” 객체

  • 총 3가지 μƒνƒœλ₯Ό κ°–λŠ”λ‹€.
    • Pending(λŒ€κΈ°): 비동기 μž‘μ—…μ΄ 아직 μ™„λ£Œλ˜μ§€ μ•Šμ€ μƒνƒœ
    • Fulfilled(이행): 비동기 μž‘μ—…μ΄ μ„±κ³΅μ μœΌλ‘œ μ™„λ£Œλ˜μ–΄, 비동기 μž‘μ—…μ˜ 결과물이 객체에 λ“€μ–΄μžˆλ‹€.
    • Rejected(μ‹€νŒ¨): 비동기 μž‘μ—…μ΄ μ‹€νŒ¨ν•œ μƒνƒœλ‘œ, μ—λŸ¬λ©”μ‹œμ§€κ°€ λ“€μ–΄μžˆλ‹€.

πŸ“Œ Promise 생성 방법

const promise = new Promise(function(resolve, reject){...});
const promise = new Promise((resolve, reject) => {...});
  • Promise κ°μ²΄λŠ” μƒμ„±μž ν•¨μˆ˜λ₯Ό 톡해 λ§Œλ“€μ–΄μ§€κ³ , 이 μƒμ„±μžλŠ” ν•¨μˆ˜λ₯Ό 인자둜 λ°›λŠ”λ‹€. 그리고 이 ν•¨μˆ˜λŠ” reslove와 rejectλΌλŠ” 2개의 ν•¨μˆ˜ν˜• νŒŒλΌλ―Έν„°λ₯Ό 가진닀.
  • μƒμ„±μž 인자둜 λ„˜μ–΄κ°€λŠ” ν•¨μˆ˜μ˜ λ°”λ””μ—μ„œλŠ” resolve()λ‚˜ reject() ν•¨μˆ˜λ₯Ό 성곡, μ‹€νŒ¨ 여뢀에 따라 적절히 ν˜ΈμΆœν•΄μ€˜μ•Ό ν•œλ‹€.

πŸ“Œ Promise μ‚¬μš© 방법

  • Promise κ°μ²΄μ—λŠ” then() λ©”μ„œλ“œμ™€ catch() λ©”μ„œλ“œκ°€ μžˆλ‹€.
  • then() λ©”μ„œλ“œ: 결과값을 가지고 μˆ˜ν–‰ν•  λ‘œμ§μ„ 담은 콜백 ν•¨μˆ˜λ₯Ό 인자둜 λ°›λŠ”λ‹€.
  • catch() λ©”μ„œλ“œ: μ˜ˆμ™Έ 처리 λ‘œμ§μ„ 담은 콜백 ν•¨μˆ˜λ₯Ό 인자둜 λ°›λŠ”λ‹€.

μ˜ˆμ‹œ

  • fetch() ν•¨μˆ˜λŠ” API의 URL을 인자둜 λ°›κ³ , API 호좜 κ²°κ³Όλ₯Ό Promise 객체둜 λ¦¬ν„΄ν•œλ‹€.
fetch("https://jsonplaceholder.typicode.com/posts/1")
  .then((response) => console.log("response:", response))
  .catch((error) => console.log("error:", error));
fetch()
  .then((response) => console.log("response:", response))
  .catch((error) => console.log("error:", error));
  • then()κ³Ό catch() λ©”μ„œλ“œλ₯Ό 톡해 동기적 μ½”λ“œμ—μ„œ μ‚¬μš©ν•˜λ˜ try-catch 블둝과 μœ μ‚¬ν•œ λ°©λ²•μœΌλ‘œ 비동기 μ½”λ“œλ₯Ό μž‘μ„±ν•  수 μžˆλ‹€.

πŸ“Œ Promise chaining

  • then()κ³Ό catch() λ©”μ„œλ“œλŠ” 또 λ‹€λ₯Έ Promise 객체λ₯Ό λ°˜ν™˜ν•œλ‹€.
  • 이 Promise κ°μ²΄λŠ” 인자둜 λ„˜κΈ΄ 콜백 ν•¨μˆ˜μ˜ 리턴값을 then()κ³Ό catch() λ©”μ„œλ“œλ₯Ό 톡해 λ‹€μ‹œ μ ‘κ·Όν•  수 μžˆλ„λ‘ ν•΄μ€€λ‹€.
  • λ”°λΌμ„œ then()κ³Ό catch() λ©”μ„œλ“œλŠ” μ—°μ‡„μ μœΌλ‘œ ν˜ΈμΆœν•  수 μžˆλ‹€.

μ˜ˆμ‹œ

fetch("https://jsonplaceholder.typicode.com/posts/1")
  .then((response) => response.json())
  .then((post) => post.userId)
  .then((userId) => "https://jsonplaceholder.typicode.com/users/" + userId)
  .then((url) => fetch(url))
  .then((response) => response.json())
  .then((user) => console.log("user:", user))
  .catch((error) => console.log("error:", error));
const promise = new Promise((resolve, reject) =>{
	resolve();
});
promise
    .then(data => {
    	throw new Error("opps");
        console.log("first value");
    })
    .catch(() => {
    	console.log("catched an error");
    })
    .then(data => {
    	console.log("second value");
    });
// catched an error
// second value

πŸ“Œ Promise.resolve()와 Promise.reject()

  • Promise.resolve()와 Promise.reject()λŠ” μžλ™μœΌλ‘œ(μ¦‰μ‹œ) μ„±κ³΅ν•˜κ±°λ‚˜ μ‹€νŒ¨ν•˜λŠ” ν”„λ‘œλ―ΈμŠ€λ₯Ό μƒμ„±ν•œλ‹€.

μ˜ˆμ‹œ

  • Promise.resolve()λŠ” μ¦‰μ‹œ ν”„λ‘œλ―ΈμŠ€λ₯Ό 성곡 μ²˜λ¦¬ν•˜λ―€λ‘œ 첫 번째 ν•¨μˆ˜κ°€ ν˜ΈμΆœλœλ‹€.
Promise.resolve("Success").then(function(value){
	console.log(value);
}, function(value){
	console.log("fail");
});
// Success
  • Promise.reject()λŠ” ν”„λ‘œλ―ΈμŠ€λ₯Ό μ¦‰μ‹œ μ‹€νŒ¨ μ²˜λ¦¬ν•˜λ―€λ‘œ then()의 두 번째 μΈμˆ˜κ°€ ν˜ΈμΆœλœλ‹€.
Promise.reject(new Error("fail")).then(function(){
	// not called
}, function(error){
	console.log(error);
});
// Error: fail

πŸ“Œ Promise.all()κ³Ό Promise.race()

✨ Promise.all()

  • λͺ¨λ“  ν”„λ‘œλ―ΈμŠ€κ°€ 성곡할 κ²½μš°μ—λ§Œ ν•˜λ‚˜μ˜ ν”„λ‘œλ―ΈμŠ€λ₯Ό λ°˜ν™˜ν•œλ‹€.

μ˜ˆμ‹œ

const promise1 = new Promise((resolve, reject) => {
	setTimeout(resolve, 500, 'first value');
});

const promise2 = new Promise((resolve, reject) => {
	setTimeout(resolve, 1000, 'second value');
});

promise1.then(data => {
	console.log(data);
});
// 500ms ν›„ first value

promise2.then(data => {
	console.log(data);
});
// 1000ms ν›„ second value
  • μœ„ μ˜ˆμ‹œμ—μ„œλŠ” 각 ν”„λ‘œλ―ΈμŠ€κ°€ μ„œλ‘œ λ…λ¦½μ μœΌλ‘œ 성곡 μ²˜λ¦¬λœλ‹€.
const promise1 = new Promise((resolve, reject) => {
	setTimeout(resolve, 500, 'first value');
});

const promise2 = new Promise((resolve, reject) => {
	setTimeout(resolve, 1000, 'second value');
});

Promise
	.all([promise1, promise2])
	.then(data => {
    	const [promise1data, promise2data] = data;
        console.log(promise1data, promise2data);
    });
// 1000ms ν›„
// first value second value
  • 1000ms ν›„ 첫 번째, 두 번째 ν”„λ‘œλ―ΈμŠ€μ˜ κ²°κ³Όκ°€ ν•¨κ»˜ λ°˜ν™˜λ˜μ—ˆλ‹€. 즉 첫 번째 ν”„λ‘œλ―ΈμŠ€κ°€ μ„±κ³΅ν•œ 이후에도 두 번째 ν”„λ‘œλ―ΈμŠ€κ°€ 성곡할 λ•ŒκΉŒμ§€ κΈ°λ‹€λ ΈμŒμ„ μ•Œ 수 μžˆλ‹€.
const promise1 = new Promise((resolve, reject) => {
	resolve("my first value");
});

const promise2 = new Promise((resolve, reject) => {
	reject(Error("opps error"));
});

Promise
	.all([promise1, promise2])
	.then(data => {
    	const [promise1data, promise2data] = data;
        console.log(promise1data, promise2data);
    });
    .catch(err => {
    	console.log(err);
    }
// Error: opps error
  • ν”„λ‘œλ―ΈμŠ€ 쀑 ν•˜λ‚˜κ°€ μ‹€νŒ¨ν•˜λ©΄ λ‹€λ₯Έ λͺ¨λ“  ν”„λ‘œλ―ΈμŠ€κ°€ μ„±κ³΅ν•˜λ”λΌλ„ ν•΄λ‹Ή μ‹€νŒ¨μ—μ„œ λ°œμƒν•œ 였λ₯˜λ₯Ό λ°˜ν™˜ν•œλ‹€.

✨ Promise.race()

  • μ΄ν„°λŸ¬λΈ”μ— ν¬ν•¨λœ ν”„λ‘œλ―ΈμŠ€λ“€ 쀑 κ°€μž₯ λ¨Όμ € 성곡 λ˜λŠ” μ‹€νŒ¨ν•œ κ²°κ³Όλ₯Ό λ°˜ν™˜ν•œλ‹€.

μ—μ‹œ

const promise1 = new Promise((resolve, reject) => {
	setTimeout(resolve, 500, 'first value');
});

const promise2 = new Promise((resolve, reject) => {
	setTimeout(resolve, 100, 'second value');
});

Promise.race([promise1, promise2]).then(function(value) {
	console.log(value);
});
// second value
  • λ‘˜ λ‹€ μ„±κ³΅ν•˜μ§€λ§Œ 두 번째 ν”„λ‘œλ―ΈμŠ€κ°€ κ°€μž₯ λ¨Όμ € μ„±κ³΅ν•˜μ—¬ κ·Έ 결과만 λ°˜ν™˜


μ°Έκ³ : [μžλ°”μŠ€ν¬λ¦½νŠΈ] 비동기 처리 2λΆ€ - Promise

post-custom-banner

0개의 λŒ“κΈ€