Promise

Dongwoo Joo·2023년 4월 24일
0

codestates bootcamp

목록 보기
32/48
var fetched = fetch('~~');
console.log('fetched', fetched);
fetched.then(function(result){});
fetched.catch(function(reason){});

then은 fetch를 통해서 실행한 결과가 성공했을 때, then으로 전달된 콜백함수가 호출되도록 약속되있다.

Fetch의 리턴값 = promise Resolve 이면, response object를 준다.

promise 사용 이유
비동기적인 작업을 처리할 때,
그 작업의 성공, 실패를 표준화된 방식을 이용해 처리할 수 있게 해준다.

성공 시, Then으로 전달된 함수 실행
실패 시, catch로 전달된 함수 실행

정보를 자바스크립트 데이터 타입으로 바꾸면, 프로그래밍이 수월하다.

Response.text
response.json => json 데이터 타입이라는 것을 자바스크립트에 알려준다.
=> 웹 브라우저는 json 데이터 타입에 맞게 데이터를 해석해서 자바스크립트의 데이터 타입으로 돌려준다.

response.json().then(function(data){
console.log('data', data);

.then(function(response){
return response.json(); => promise를 리턴
})
.catch(function(reason){
console.log('reason', reason);

promise 사용 2가지 방법
Nested promise
then 안에 then

promise chaining
then 안에서 promise를 리턴

profile
pursue nature

0개의 댓글