Js / 비동기 (2)

초짜의 개발 공부·2021년 9월 1일
0

비동기

목록 보기
2/2
post-thumbnail

1. fs(file system) 모듈..?

Node.js는 로컬 컴퓨터로 직접 실행하기 때문에 모듈을 통해서 파일을 읽고 저장하기가 가능하다. 그래서 파일을 읽는 비동기 함수를 제공하는데 fs 모듈을 통해서 사용법을 익히자. 내가 사용할 모듈은 fs.readFile이다. (fs의 모듈 종류는 굉장히 많으니 더 자세한 내용은 공식문서를 통해 살펴보자.)



공식문서를 바탕으로 살펴보면

fs.readFile (path[, options], callback)

readFile에서는 path, options, callback을 가져올 수 있다.

- path

< 문자열 >,< 버퍼 >,< URL >,< 정수 > 인데 가져올 파일 이름을 표시하면된다.

- options

< 오브젝트 >, < 문자열 >

- callback

< err :오류 >
< data : 문자열, 버퍼 >



// ex )


fs.readFile(filePath, 'utf8',(err, data) => {
  if(err) throw err;	
  console.log(data)
})



2. fetch API(Application Programming Interface)


비동기 요청 중 하나는 네트워크 요청이다. 네트워크를 통한 요청의 형태는 다양하지만 가장 흔한 URL를 이용해보자. URL은 fetch API를 통해 요청이 가능하다. 원격URL을 fetch API를 통해 불러와서 특정 정보를 받아올 수 있다. fetch API를 쓰려면 Promise를 사용할 줄 알아야 한다. return 값이 Promise 객체이기 때문이다.
fetch에는 request, response 객체가 포함 되어 있다.(자세한 내용은 생략)


- 기본 형식


fetch('http://example.com/example.json')
  .then(function(response) {
    return response.json();
  })
  .then(function(myJson) {
    console.log(JSON.stringify(myJson));
  });

- fetch API를 통해 Promise.all()/ async await 사용하기


  • Promise.all()

const exampleURL1 = 'http://localhost:5000/data'
const exampleURL2 = 'http://localhost:5000/data'

// ex 1) 

function dataAll() {
  let data1 = fetch(exampleURL1).then(response => response.json())
  let data2 = fetch(exampleURL2).then(response => response.json())
	return Promise.all([data1, data2]).then(data0 => {
     let obj = {}
     obj.value1 = data0[0].data, 
     obj.value2 = data0[1].data
       return obj
    })
}

//ex 2)


return Promise.all([fetch(exampleURL1),fetch(exampleURL2)])
	.then(([aResponse, bResponse])=> {
	  return Promise.all([aResponse.json(), bResponse.json()])
	}).then(([data1,data2])=>{
		return {
          value1 : data1.data,
          value2 : data2.data
          }
		}) 



- async await

async function dataAsync() {
 const exampleURL1 = 'http://localhost:5000/data'
 const exampleURL2 = 'http://localhost:5000/data'

 
 
 const data1 = await fetch(exampleURL1).then((response) => response.json())
 const data2 = await fetch(exampleURL2).then((response) => response.json())
 
 return {
 	value1 : data1.data,
    value2 : data2.data
 }
}
 

0개의 댓글