본문 바로가기

JavaScript

5주차_자바스크립트

5주차_자바스크립트

 

동기와 비동기의 차이

 

동기 방식

 

하나의 코드가 끝난 다음에, 다음의 코드가 실행되는 것을 의미합니다.

 

비동기 방식

 

1번 코드가 끝나지 않았음에도, 그 다음 코드들을 호출하게 되는 것을 의미합니다.

 

동기 방식 VS 비동기 방식

 

비동기 방식

왜냐하면, 여러 가지를 동시에 처리를 할 수 있기 때문입니다.

 

// 비동기 문제 예시1

log("1st");
log("2nd");
log("3rd");

// 실행 결과 : 1st 2nd 3rd

----------------------------------------------------

// 비동기 문제 예시2

log("1st")
setTimeout(() => {
 log("2nd")
}, 1000)
log ("3rd")

// 실행 결과 : 1st 3rd 2nd

----------------------------------------------------

// 비동기 문제 예시 3

//이름과 나이를 받아서 student에 저장
const getStudent1 = (name, age) => {
	let student
		
    setTimeout{() => {
    student = {name, age}
    }, 1000)

	return student
}

----------------------------------------------------

const studentA = getStudent1("오태관", 20)
log(`학생의 이름은 ${studentA.name}이고, 나이는 ${studentA.age}살이다.`)

// 실행 결과
log(`학생의 이름은 ${studentA.name}이고, 나이는 ${studentA.age}살이다.`)

//TypeError : Cannot read properties of undefined (reading 'name') 발생

// 콜백 함수를 이용한 비동기 처리
const getStudent2 = (name, age, func) => {
	let student

	setTimeout(() => {
	student = {name, age}
	func(student)
	}, 1000}
}

getStudent2("오태관", 20, (student) =>
	log(`학생의 이름은 ${student.name}이고, 나이는 ${student.age}살이다.`);
)

 

Promise

 

예외처리로 얻게 된 값을 Promise를 통해 쉽게 얻을 수 있습니다.

한마디로 표현하자면, 비동기 처리를 생각해서 원하는 값을 받아낼 수 있습니다.

 

 

Async

 

Function 앞에 Async를 붙이면 해당 함수는 Promise를 반환합니다.

Promise가 아닌 값을 반환하더라도 이행 상태의 Promise로 값을 감싸 이행된 Promise가 반환되도록 한다

 

Await

 

Await를 만나면 Promise가 처리될 때까지 기다립니다. 

결과는 그 이후 반환됩니다.

 

Async와 Await의 문법을 사용하면 Promise를 좀 더 편하게 사용할 수 있습니다.

 

// promise 생성
const promise = new promise((resolve, reject) => {})

const getStudent3 = (name, age) => {
	return new Promise((resolve, reject) => {
	setTimeout(() => {
		if(!name) reject(new Error("undefined Name"))
		student = {
			name : name,
			age : age,
			}
			resolve(student)
			}, 1000)
			})
		}

		getStudent3("오태관", 20)
		.then((student) => 
			log(`학생의 이름은 ${student.name}이고, 나이는 ${student.age}살이다.`)
		)
		catch((err) => console.log(err))
        
-----------------------------------------------------------------------------------

//Async, await 키워드를 이용한 비동기 처리

const getStudent3 = (name, age) => {
	return new Promise((resolve, reject) => {
	setTimeout(() => {
		if(!name) reject(new Error("undefined Name"))
		student = {
			name : name,
			age : age,
			}
			resolve(student)
			}, 1000)
			})
		}
const getStudent = async () => {
	try{

	const student = await getStudent3("오태관", 20)
	log(`학생의 이름은 ${student.name}이고, 나이는 ${student.age}살이다.`)
	} catch(err){
		console.log(err)
	}
}
getStudent()