Promise

공룡개발자·2022년 3월 31일
0

동기 | 비동기

	// 동기적인 경우
	console.log(1);
	console.log(2);
	console.log(3);
	console.log(4);
	
	// 1
	// 2
	// 3
	// 4

	// 비동기적인 3번째 경우
	console.log(1);
	console.log(2);
	setTimeout(() => console.log(3), 5000);
	console.log(4);
	
	// 1
	// 2
	// 4
	// 3

'synchronous하다.' 즉, 동기적이라는 말은 순차적으로 실행됨을 의미하고,
'asynchronous하다.' 즉, 비동기적이라는 말은 병렬적으로 자신의 시간표대로 실행됨을 의미한다.

Fetch API

Fetch API의 반환값은 'A Promise that resolves to a Response object.'이다.

	let fetched = fetch('https://jsonplaceholder.typicode.com/posts')
  	
    // fetch를 통해서 실행한 결과가 성공적일때, then함수가 시행되고 Response 객체를 반환!
    fetched.then(function(reponse){console.log('result', response)}
    // result Response {type: 'cors', url: 	'https://jsonplaceholder.typicode.com/posts', redirected: false, status: 200, ok: true, …}

Promise를 사용하는 이유는 비동기적인 작업을 처리할 때 그 작업의 성공 유무를 표준화된 방식을 이용해 처리할 수 있게 한다.
성공했을 때는 then으로 전달된 함수를 실행.
실패했을 때는 catch로 전달된 함수를 실행.

일반적으로 아래와 같이 사용한다.

	fetch('https://jsonplaceholder.typicode.com/posts')
		.then(function(response){
      		return response.json()
      // reponse가 json 데이터 타입이라는 것을 js에 알려주는 것
      // 또 Promise를 반환
    	})
		.catch(function(reason){
      		console.log('reason', reason)
    	})
		.then(function(data){
      		console.log('data', data)
    	})
profile
공룡의 발자취

0개의 댓글