JavaScript
[ JS ] Promises
Design-loving front-end engineer
2022. 7. 6. 08:05
🔴 Using Promises

const test = new Promise((resolve, reject) => {
// If Promise ends successfully,
setTimeout(resolve, 2000, "Promise end successfully!");
// === resolve("Promise end successfully!");
// If Promise return error
setTimeout(reject, 2000, "Promise return error!");
});
test.then(result => console.log(result)) // resolve => then❗
.catch(error => console.log(error)); // reject => catch❗
🟠 Chaining Promises

const test = new Promise((resolve, reject) => {
resolve(2); // then에 2 전달
});
test.then(nubmer => {
console.log(number * 2); // 4
return number * 2; // for Promise Chaining❗
})
.then(otherNumber => {
console.log(otherNumber * 2); // 8
});

const test = new Promise((resolve, reject) => {
resolve(2); // then에 2 전달
});
const timesTwo = number => number * 2;
test
.then(timesTwo)
.then(timesTwo)
.then(timesTwo)
.then(timesTwo)
.then(timesTwo)
.then(() => {
throw Error("Something is wrong");
})
.then(lastNumber => console.log(lastNumber))
.catch(error => console.log(error)); // Error: Something is wrong
🟡 Promise.all
⚪ 모든 promise가 동시에 동작하는지 확인하는게 중요할 때 사용한다.
⚪ 하나의 promise라도 reject 된다면 에러를 발생시키며, 이후 promise는 실행하지 않는다.

const p1 = new Promise(resolve => {
setTimeout(resolve, 10000, "First");
});
const p2 = new Promise(resolve, reject) => {
setTimeout(reject, 1000, "Not Second, Error");
});
const p3 = new Promise(resolve => {
setTimeout(resolve, 3000, "Third");
});
const motherPromise = Promise.all([p1, p2, p3]);
// 모든 Promise의 resolve가 실행되고 나서 한꺼번에 값이 then으로 넘어감❗
motherPromise
.then(values => console.log(values))
.catch(error => console.log(error));
🟢 Promise.race

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");
});
// p1, p2, p3 중 resolve, reject에 상관없이 가장 빨리 실행되는 것을 넘겨준다❗
Promise.race([p1, p2, p3])
.then(values => console.log(values))
.catch(error => console.log(error));
🔵 allSettled
⚪ 모든 promise가 모두 잘 동작하는지 확인할 필요가 없을 때 allSettled를 사용한다.
⚪ 일부는 동작하고, 일부는 동작하지 않아도 response와 error를 같이 출력해준다.

const p = Promise.allSetteld([
fetch("https://yts.mx/api/v2/list_movies.json"),
fetch(),
fetch("https://yts.mx/api/v2/list_movies.json"),
fetch(),
]);
.then(response => console.log("Success!", response))
.catch(error => console.log("Error: ", error));
🟣 .finally

const p1 = new Promise((resolve, reject) => {
setTimeout(reject, 5000, "First");
})
.then(value => console.log(value))
.catch(error => console.log(error))
.finally(() => console.log("I'm done"));
// finally :: then이나 catch에 상관없이 무조건 실행된다❗
🟤 Real world Promises

fetch("http://127.0.0.1:8080/")
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log(error));
// API에 데이터를 요청하면 response를 받게된다.
// response는 json 형태가 아니기 때문에 .text()로 데이터를 변환시킨다.
// 그 과정에서 또 하나의 Promise가 발생한다.