동기 : 순차적으로 동작 like 싱글쓰레드. 마치 계주에서 바통을 가지고있는 사람만 달릴 수 있는것 처럼 다른 함수를 기다리다가 차례가 되면 동작함.
비동기 : 여러명이 일하는것 처럼 like 멀티쓰레드. 한번에 여러일을 할 수 있음.
callback 함수
함수에 파라미터로 들어가는 함수.
순차적으로 실행하고 싶을 때 씀.
const 버튼 = document.querySelector('.button');
버튼.addEventListener('click', 콜백함수(){}); // 이렇게 함수에 파라미터로 들어가는 함수가 콜백함수.
Promise
비동기 처리에 사용되는 객체
promise의 생성자 함수는 resolve와 reject함수를 인자로 전달받는 콜백함수를 인자로 받음.
성공(fulfilled)되면 resolve함수 호출, 실패(rejected)하면 reject함수 호출
then : resolve 호출시 실행. 기본적으로 프로미스 반환
catch : 에러(예외)가 발생하면 호출. 프로미스 반환
const promise = () => new Promise((resolve, reject) => { // promise라는 이름의 전역 변수에 프로미스 함수 할당,
// a가 3이면 resolve 호출, 아니면 reject 호출
let a = 1 + 1
if(a == 3) {
resolve('success')
} else {
reject('failed')
}
})
promise().then((message) => { // resolve 호출시 실행
console.log('This is in the then ' + message) // This is in the then success
}).catch((error) => { // reject 호출시 실행
console.log('This is in the catch ' + error) // This is in the catch failed
})
let p = new Promise(function(resolve, reject) {
resolve('hello world'); // resolve 호출
}).then(메시지 => {
alert(메시지); // hello world
return 메시지.split(' ')[0]
}).then(메시지 => {
alert(메시지); // hello
return 메시지[0]
}).then(메시지 => {
alert(메시지); // h
});
let p = new Promise(function(resolve, reject) {
reject('hello world'); // reject 호출
}).then(메시지 => {
alert(메시지);
return 메시지.split(' ')[0]
}).then(메시지 => {
alert(메시지);
return 메시지[0]
}).then(메시지 => {
alert(메시지);
}).catch(메시지 => { // reject 이므로 catch가 실행됨.
alert('catch 실행!! :' + 메시지); // catch 실행!! :hello world
});
fetch() : 인자로 url이 들어가며 해당 주소에 리소스를 비동기 요청. 주로 API를 호출하고 응답 데이터를 받아오는 데에 사용됨. 프로미스 객체 반환.
fetch("https://jsonplaceholder.typicode.com/posts") // defualt로 http 메소드 중 GET으로 동작
.then(function(res){ // 주소에 요청을 보낸후 응답 객체(res)를 받음
return res.json(); // res 객체의 json() 메서드 사용. body의 텍스트를 promise형태로 반환.
})
.then(function(json){ // 반환받은 json값을 받아서 처리.
console.log(json); // json값들이 log로 출력
});
async : 함수 선언에 사용. 프로미스 반환
await : async 함수 내부에서만 사용. then 대신 사용. promise 객체가 완료될 때 까지 기다림. promise 가 resolve 한 값 반환.
async function promise(){
let a = 1 + 1;
if (a == 3){
return 'success';
} else {
throw new Error('failed');
}
}
promise(); // Error: failed
function getTitle(){ // fetch를 통해 response 데이터를 받아서 json으로 리턴
const response = fetch("https://jsonplaceholder.typicode.com/posts"); // response는 promise 객체
return response.then(res => res.json()); // 만약 async함수 였다면 return await response로 가능
}
async function exec(){ // async사용
var text;
try { // try catch문으로 오류 판별
text = await getTitle(); // await으로 getTitle완료까지 기다림.
//await를 안쓰면 getTitle.then((json){text=json;})
console.log(text[0].title);
}
catch(error){
console.log(error);
}
}
exec();
'JS' 카테고리의 다른 글
JS 프로젝트 - Computer AI (0) | 2023.09.08 |
---|---|
JS 실습 - 쇼핑몰 간단하게 만들기 (0) | 2023.08.28 |
JS(13) DOM(Document Object Model) (0) | 2023.08.26 |
JS(12) JSON (0) | 2023.08.25 |
JS(11) 전개구문과 디스트럭쳐링(구조 분해 할당) (0) | 2023.08.25 |