- 선언 const promise = new Promise((resolve, reject) => {resolve(성공할때 호출할 값)}
- 프라미스 사용 promise.then(resolve 값=>{ ~ }).then(~의 결과값=>{})...
<주의해야 하는것>
프라미스의 then이 반환하는 것은 특정값이 아닌 promise 객체다.
프라미스의 결과값을 다루려면 then((result)=>여기서 다루어야 한다)
then은 결과나 에러를 체인 아래로 전달한다.
promise.then(f1).catch(f2); // f1에서 에러가 발생하면 .catch에서 에러가 처리된다. promise.then(f1, f2); //이어지는 체인이 없기 때문에 f1에서 발생한 에러를 처리하지 못한다.
1. GET(조회):
fetch('http://example.com/movies.json')
.then((response) => response.json())
.then((data) => console.log(data));2. POST(추가) :
const newdata = { 새로운 정보 }
fetch('http://example.com/movies.json', {
method: 'POST',
body: JSON.stringfy(newdata)
})
.then((response) => response.json())
.then((data) => console.log(data)); // 응답은 서버마다 다르게 출력 (추가된 데이터 정보 보려면 get으로 확인)3. PUT(수정-덮어쓰기) :
const newdata = { 수정 정보 전체 입력 }
fetch('http://example.com/movies.json', {
method: 'PUT',
body: JSON.stringify(newdata)
})
.then((response) => response.json())
.then((data) => console.log(data));4. PATCH(수정-일부) :
const newdata = { 갱신, 수정하고 싶은 정보만 입력 }
fetch('http://example.com/movies.json', {
method: 'PUT',
body: JSON.stringify(newdata)
})
.then((response) => response.json())
.then((data) => console.log(data));DELETE(삭제) :
fetch('http://example.com/movies.json/2(id값특정)', {
method: 'DELETE'
})
.then((response) => response.json())
.then((data) => console.log(data));