js_8

정혜지·2022년 8월 8일
0

비동기 프로그래밍

promise

pending
fulfilled
rejected

.then 비동기적인것을 동기적으로 처리할 수 있는 연결함수
배열함수의 filter처럼 사용가능

일반적 promise문

promise
	try {
    	setTimeout(() => {
        	noSuchElement;
      	}, 1000)
    } catch (error) {
      	console.log(error)
    } finally {
      	console.log('무조건 실행되는 코드 블럭')
    }

filter처럼

promise
	.then(v => {console.log(v)})
    .then(() => {console.log(1)})
    .then(() => {console.log(2)})
    .catch(err => {console.log(err)})
    .finally(() => {console.log('무조건 실행되는 코드블럭')})

console.log(promise) --> 프로미스 객체를 반환
프로미스 객체 : 실제 정상 기능이 수행된 상태의 데이터가 담겨 있는 객체
프로미스 객체 : 생산자
then 소비자함수로 연결하여 사용 (프로미스객체가없다면 사용불가X)

catch 문법 필요
.catch(err => {console.log(err)})
catch 소비자함수

catch 에러처리

fetch

https://developer.mozilla.org/ko/docs/Web/API/Fetch_API
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

fetch 내장객체

xhr

function ajaxTest() {
      var xhr = new XMLHttpRequest()

      xhr.onreadystatechange = function() {
       
        if (this.readyState == 4 && this.status == 200) {
          	console.log(this)
        }
      }

	xhr.open('GET', 'https://jsonplaceholder.typicode.com/users', true)
	xhr.send()
}

    ajaxTest()

fetch

fetch('https://jsonplaceholder.typicode.com/users')   
// = return new Promise  --> then 소비자함수 사용가능
      .then((response) => response.json())
      .then((users) => {console.log(users)})

fetch 실습
https://jsonplaceholder.typicode.com/posts/1

axios 실습
https://axios-http.com/kr/docs/intro

Axios
비동기 통신을 위한 프로미스 기반의 *라이브러리

라이브러리(도구) VS 프레임워크(도구모음팩)

fetch : post, put, delete --> axios post, put, delete

  axios.post("https://jsonplaceholder.typicode.com/posts",{
    userId: 1,
    title: "post testting!",
    body: "post testing!"
  }).then((response) => {console.log(response)})

  axios.put('https://jsonplaceholder.typicode.com/posts/1', {
    title: 'JS',
    body: 'js'
  }).then((response) => {console.log(response.data)})

  axios.delete('https://jsonplaceholder.typicode.com/posts/1')
    then((response) => {console.log(response.data)})

간단히

let url = 'https://jsonplaceholder.typicode.com/users'
  const newObj = {
    userId: 1,
    title: "post testting!",
    body: "post testing!"
  }
 axios.post(url, newObj)
    .then((response) => {console.log(response)})
    

  url = https://jsonplaceholder.typicode.com/posts/

  axios.put(`${url}/1`, {
    title: 'JS',
    body: 'js'
  }).then((response) => {console.log(response.data)})

  axios.delete(`${url}/1`)
    then((response) => {console.log(response.data)})

// 객체 비구조화 할당
const obj = {
a: 1,
b: 2,
name: 'it'
}
console.log(obj.b)

const {a, b, name, c=0} = obj
console.log(name)
console.log(c)

REST(...)

배열

const avengers = ['토르', '스파이더맨', '닥터']
  const totalAvengers = [...avengers, '미스제인']
  console.log(avengers)
  console.log(totalAvengers)

객체

const planet = {
    continent: 'Asia'
  }
  
  const country = {
    // continent: 'Asia'
    ...planet,
    countryName: 'ROK'
  }
  
  const city = {
    // continent: 'Asia'
    // countryName: 'ROK'
    ...country,
    region: 'Busan'
  }

함수

function sum(...rest) {
    // console.log(rest)   //배열
    return rest.reduce((accumulator, currentValue) => (accumulator + currentValue), 0)
  }
  sum(1, 2, 3)
  console.log(sum(1,2,3,5,23,5))

API
실제 넘겨져 온 데이터를 활용하는 방법
https://dog.ceo/dog-api/
https://dog.ceo/api/breeds/image/random

profile
오히려 좋아

0개의 댓글