상세 컨텐츠

본문 제목

[자바스크립트] promise

카테고리 없음

by esoesmio 2023. 5. 17. 17:31

본문

프로미스 시작단계 써봐라

 

const promise1 = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve('foo');
    }, 300);
});

promise1.then((value) => {
    console.log(value);
    // Expected output: "foo"
});

console.log(promise1);
// Expected output: [object Promise]

돈빌리는 약속 시간없이

 

 

const borrow = 20;

// 빌린 돈의 10%를 더해 값겠다는 약속
// reject는 지금 사용하지 않음
const payWith10perc = new Promise((resolve, reject) => {
  resolve(borrow * 1.1);
});

payWith10perc
.then(result => {
  console.log(result + '만원');
});

 

 

이 코드는 JavaScript의 Promise와 then 메서드를 사용하여 비동기 처리를 하고 있습니다. 아래에 각 부분에 대해 자세히 설명하겠습니다.

  1. const borrow = 20; - 이 부분은 'borrow'라는 상수를 선언하고 그 값으로 '20'을 할당합니다. 이는 빌린 돈을 나타냅니다.
  2. const payWith10perc = new Promise((resolve, reject) => { resolve(borrow * 1.1); }); - 이 부분에서 'payWith10perc'라는 새 Promise 객체를 생성합니다. Promise는 JavaScript에서 비동기 작업을 쉽게 처리할 수 있도록 도와주는 객체입니다. Promise는 보통 네트워크 요청이나 파일 시스템에서 읽기와 같은 비동기 작업에서 사용됩니다. Promise는 세 가지 상태를 가집니다: 대기(pending), 이행(fulfilled), 거부(rejected). 이 경우, Promise는 'resolve' 함수를 통해 즉시 이행 상태로 변경되며, 'borrow' 값의 10%를 더한 값을 결과로 반환합니다.
  3. payWith10perc .then(result => { console.log(result + '만원'); }); - 이 부분에서는 'then' 메서드를 사용하여 Promise가 이행되었을 때 실행할 코드를 정의합니다. 'then' 메서드는 Promise가 이행되었을 때 호출되는 콜백 함수를 인자로 받습니다. 이 콜백 함수는 Promise가 반환하는 결과를 인자로 받아 실행됩니다. 여기서는 결과값에 '만원'이라는 문자열을 더해 콘솔에 출력하고 있습니다.

따라서 이 코드는 빌린 돈에 10%를 더한 값을 출력하는 비동기 작업을 수행합니다.

 

 

 

 

돈빌리는 시간

 

const borrow = 20;

const payWith10perc = new Promise((resolve, reject) => {
  // 💡 내부에서 비동기 코드 사용
  setTimeout(() => {
    resolve(borrow * 1.1);
  }, 1000); // 1초 후 갚겠음
});

// ⚠️ 콘솔에서 분리해서 실행하면 안 됨!
// 프로미스가 생성되는 순간부터 시간 경과
payWith10perc
.then(result => {
  console.log(result + '만원');
});

 

then 연속적으로 chaining

 

// ⭐ then은 연속적으로 메서드 체이닝 가능

new Promise((resolve) => {
  resolve(2);
})
.then(i => i * 4)
.then(i => i - 3)
.then(i => i ** 2)
.then((i) => {
  console.log(i);
});

 

 

돈 다섯번 빌려주고 파산하는거

 

// 빌린 금액으로 약속을 하는 함수
function moneyLend (borrow) {
    return new Promise((resolve, reject) => {
        console.log(`채무 ${borrow}만원`);

        setTimeout(() => {
            if (Math.random() < 0.1) {
                reject('채무자 파산');
            }

            resolve(borrow * 1.1);
        }, 1000);
    });
}

moneyLend(20)
    .then(moneyLend)
    .then(moneyLend) // 인자를 하나 받아서 그대로 쓰므로
    .then(moneyLend) // 이렇게 줄여버릴 수 있음
    .then(moneyLend)
    .then(result => {
        console.log(`💰 반납 ${result}만원`);
    })
    .catch(msg => {
        console.error(msg);
    })
    .finally(() => {
        console.log('- - 대금업 종료 - -');
    });

릴레이예제 프로미스로 구현

 

const DEADLINE = 1400;

function getRelayPromise (name, start, failMsg) {
    console.log(`👟 ${name} 출발`);

    // 💡 랜덤 시간만큼 달리고 결과를 반환하겠다는 약속을 만들어 반환
    return new Promise((resolve, reject) => {
        const time = 1000 + Math.random() * 500;

        setTimeout(() => {
            if (time < DEADLINE) {
                console.log(`🚩 ${name} 도착 - ${(start + time)/1000}초`);
                resolve(start + time);
            } else {

                console.log(failMsg);
                reject((start + time) / 1000);
            }
        }, time);
    })
}
getRelayPromise('철수', 0, '철수부터 광탈입니다. ㅠㅠ')
    .then(result => {
        return getRelayPromise('영희', result, '영희가 완주하지 못했네요.');
    })
    .then(result => {
        return getRelayPromise('돌준', result, '돌준이 분발해라.');
    })
    .then(result => {
        return getRelayPromise('정아', result, '정아에게 무리였나보네요.');
    })
    .then(result => {
        return getRelayPromise('길돈', result, '아아, 아깝습니다...');
    })
    .catch(msg => {
        console.log(`😢 완주 실패 - ${msg}초`);
    })
    .finally(() => {
        console.log('- - 경기 종료 - -');
    });

댓글 영역