Promise
는 비동기 처리에 사용되는 객체이다.Promise
가 생성된 시점에는 정해지지 않았을 수 있는 결과를 나중에 돌려주겠다는 약속(promise)을 반환하는 것이다. 이는 콜백 함수의 단점을 보완할 수 있다.
new Promise(function(resolve, reject) {
// ...
});
new Promise(function(resolve, reject) {
resolve();
});
new Promise(function(resolve, reject) {
reject();
});
then()
: Promise가 성공적으로 해결되면 실행되며 결과를 인자로 받는다.catch()
: Promise가 거부되면 실행되며 에러를 인자로 받는다.function waitForTwoSeconds() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve("Waited for 2 seconds");
}, 2000);
});
}
console.log("Start");
waitForTwoSeconds()
.then(function(result) {
console.log(result);
})
.catch(function(error) {
console.log(error);
});
console.log("End");
❗️결과 출력
Start
End
Waited for 2 seconds
Promise chaining은
then()
메서드를 이용하여 연속적인 비동기 작업을 처리하는 방식이다. Promise chaining을 사용하면 각각의 비동기 작업을 순차적으로 실행하고, 이전 작업의 결과를 다음 작업에 전달할 수 있다.
function waitTwoSeconds() {
return new Promise(resolve => {
setTimeout(() => {
resolve('Waited for 2 seconds');
}, 2000);
});
}
waitTwoSeconds()
.then(result => {
console.log(result);
return 'This is the next step';
})
.then(result => {
console.log(result);
return 'This is the final step';
})
.then(result => {
console.log(result);
})
.catch(error => {
console.error(error);
});
❗️결과 출력
Waited for 2 seconds
This is the next step
This is the final step
fetch()
함수는 request, jQuery, axios 같은 라이브러리를 대신해 사용할 수 있는 브라우저 내장 함수중 하나로 네트워크를 통해 리소스를 가져오는 기능을 한다.
fetch()
함수는Promise
를 반환하며, 이Promise
는 HTTP 응답(Response)을 나타내는Response
객체를 반환한다.
fetch()
와 jQuery.ajax()
의 차이점➡️ fetch()
가 반환하는 Promise
객체는 404, 500과 같은 HTTP 오류 상태를 수신해도 거부되지 않고 .then
을 통해 처리된다.
fetch(url,options)
.then((response) => response.json())
.then((data) => console.log(data));
.catch(error => console.error('Error:', error));
fetch()
함수는 디폴트로 GET
방식으로 작동한다. GET
은 요청 전문을 받지 않기 때문에 옵션 인자를 쓰지 않는다.
fetch(url)
.then((response) => response.json())
.then((data) => console.log(data));
.catch(error => console.log(error));
위 방식으로 호출하면 response 객체로부터 JSON 포멧의 응답 전문을 자바스크립트 객체로 변환하여 얻을 수 있다.
POST
요청을 보내기 위해서는, fetch()
함수의 두 번째 인자, 즉 옵션 인자로 요청에 대한 구성을 객체로 전달해야 한다. 객체의 속성으로는 method
, headers
, body
등을 설정할 수 있다.
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then((response) => response.json())
.then((data) => console.log(data));
.catch(error => console.log(error));
GET
과 마찬가지로 응답 객체의 json() 메서드를 호출해서 응답 전문을 객체 형태로 얻을 수 있다.
PUT
요청은 주로 데이터를 수정해야 할 때 사용하며 POST
와 유사하게 사용한다.
fetch(url, {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then((response) => response.json())
.then((data) => console.log(data));
.catch(error => console.log(error));
DELETE
요청은 데이터를 삭제할 때 사용되며 보내는 데이터가 없다. 따라서 header
와 body
옵션이 필요하지 않다.
fetch(url, {
method: "DELETE",
)}
.then((response) => response.json())
.then((data) => console.log(data));
.catch(error => console.log(error));