
[250122 수요일]
개인과제를 하면서 어느정도 비동기를 이해했다고 생각했는데, 왜 문제은행만가면 멍...무슨소린지 모르겠는가?
그래서 다시 한번 개념만 호로록!
자바스크립트에서 Promise는
Promise가 비동기 작업을 아직 처리 중인 상태로 결과가 나올 때까지 기다린다.
비동기 작업이 성공적으로 완료되어, 결과값을 반환한 상태.
비동기 작업이 실패하거나 오류가 발생한 상태.
이 경우, 오류 정보를 반환.
Promise는 새로운 객체를 생성할 때, 실행할 비동기 작업을 정의한 함수 (executor)를 인자로 받는다. 이 함수의 인자는 resolve와 reject 두 가지.
resolve: 비동기 작업이 성공적으로 완료되었을 때 호출.reject: 비동기 작업이 실패했을 때 호출.let promise = new Promise((resolve, reject) => {
let success = true; // 작업의 성공 여부를 나타내는 변수
if (success) {
resolve('작업 성공!');
} else {
reject('작업 실패!');
}
});
//문제은행 코드
let resolvePromise= Promise.resolve("Hello");
let rejectPromise = Promise.reject("Error!");
Promise 객체는 then()과 catch() 메서드를 사용해 결과를 처리한다.
then(onFulfilled, onRejected): 작업이 성공하면 onFulfilled 콜백이 실행되고, 실패하면 onRejected 콜백이 실행된다.catch(onRejected): then과 동일하게 실패한 경우 onRejected 콜백만 처리.promise
.then(result => {
console.log(result); // '작업 성공!' 출력
})
.catch(error => {
console.log(error); // 실패한 경우에만 호출
});
Promise는 체이닝(chaining) 방식으로 여러 비동기 작업을 순차적으로 처리할 수 있다. 각 then() 호출은 새로운 Promise를 반환하기 때문에, 여러 개의 then()을 연결하여 작업을 처리할 수 있다.
let promise = new Promise((resolve, reject) => {
resolve(1);
});
promise
.then(result => {
console.log(result); // 1 출력
return result + 1; // 다음 then으로 넘길 값
})
.then(result => {
console.log(result); // 2 출력
return result + 1;
})
.then(result => {
console.log(result); // 3 출력
});
Promise를 좀 더 직관적이고 동기적인 방식으로 다룰 수 있게 해주는 문법(...아마도), async 함수는 항상 Promise를 반환하고, await는 Promise가 처리될 때까지 기다린다.
async/await를 사용할 때, try...catch 구문을 사용하여 비동기 작업에서 발생할 수 있는 에러를 처리한다..
const url = "https://jsonplaceholder.typicode.com/posts/1/comments";
const comments = async function (url) {
try {
const resComments = await fetch(url);
const resComments2 = await resComments.json();
console.log("comments => ", resComments2);
} catch (error) {
console.log("에러발생 >> ", error);
}
};
다시 문제를 보고 풀려고 하면 잘 풀릴까?
풀었던 문제도 텀을 두고 계속 반복 복습!