동기식 처리 모델(Synchronous processing model)은 직렬적으로 작업을 수행한다. 작업은 순차적으로 실행되며 어떤 작업이 수행 중이면 다음 작업은 대기하게 된다. 예를 들어 서버에서 데이터를 가져와 화면에 표시하는 작업을 수행할 경우 서버에 데이터를 요청하고 데이터가 전달될 때까지 이후 작업들은 중단(Blocking)된다.
function first() {
console.log('first');
second();
}
function second() {
console.log('second');
third();
}
function third() {
console.log('third');
}
first();
위 예시는 동기식으로 동작하는 코드로 순차적으로 실행된다. (first => second => third 순)
비동기식 처리 모델(Asynchronous processing model or Non-Blocking processing model)은 병렬적으로 작업을 수행한다. 즉, 작업이 종료되지 않은 상태라도 대기하지 않고 다음 작업을 실행한다.
function first() {
console.log('first');
second();
}
function second() {
setTimeout(function() {
console.log('second');
}, 0);
third();
}
function third() {
console.log('third');
}
first();
위 예시는 비동기식으로 동작하는 코드로 순차적으로 실행되지 않는다. (first => third => second 순)
Ajax(Asynchronous JavaScript and XML)는 자바스크립트를 이용해서 비동기적(Asynchronous)으로 서버와 브라우저가 데이터를 교환할 수 있는 통신 방식을 의미한다.
서버로부터 웹페이지가 반환되면 화면 전체를 갱신해야 하는데 페이지 일부만을 갱신하고도 동일한 효과를 볼 수 있도록 하는 것이 Ajax이다. 페이지 전체를 로드하여 렌더링할 필요가 없고 갱신이 필요한 일부만 로드하여 갱신하면 되므로 빠른 퍼포먼스와 부드러운 화면 표시 효과를 기대할 수 있다.
1) jQuery 설치하여 $.ajax() 사용
2) axios 설치하여 axios.get() 사용
3) 순수 자바스크립트 문법 fetch() 사용
//data.js
export default [
{
id : 0,
title : "Black Jacket",
content : "Born in Paris",
price : 6000000
},
{
id : 1,
title : "White Bag",
content : "Born in Paris",
price : 5000000
},
{
id : 2,
title : "Black Bag",
content : "Born in Paris",
price : 4000000
},
]
//App.js
<button className='btn btn-primary' onClick={()=>{
axios.get('https://codingapple1.github.io/shop/data2.json')
.then(()=>{
console.log('success');
})
.catch(()=>{
console.log('fail');
})
}}>더보기</button>
function MyComponent() {
const [error, setError] = useState(null);
const [isLoaded, setIsLoaded] = useState(false);
const [items, setItems] = useState([]);
useEffect(() => {
fetch("https://api.example.com/items")
.then(res => res.json())
.then(
(result) => {
setIsLoaded(true);
setItems(result);
},
(error) => {
setIsLoaded(true);
setError(error);
}
)
}, [])
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<ul>
{items.map(item => (
<li key={item.id}>
{item.name} {item.price}
</li>
))}
</ul>
);
}
}