Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- css variables
- 정규표현식
- Engoo
- flex-shrink
- JS
- regExp
- Express
- Prototype
- node
- css grid
- flexbox
- flex-grow
- 무료 백엔드 배포
- close together
- flex-basis
- css 오버레이
- select by attribute
- express-handlebars
- Node.js
- 디자인패턴
- es6
- Sass
- improve-iq-by-up-to-10%!
- img 확대
- shit-christmas
- just-one-small-sip
- css
- Object.create
- module wrapper function
- ajax
Archives
- Today
- Total
Callback function 본문
Callback
다른 함수의 인자로 전달되는 함수를 뜻한다.
아래의 코드를 실행해보면 setTimeout이 비동기적 처리를 하기 때문에 새로 추가한 포스트가 getPost 메서드를 통해 표출되지 않는다.
const posts = [
{
title: "Post One",
body: "This is post one"
}, {
title: "Post Two",
body: "This is post Two"
}
];
function createPost(post) {
setTimeout(function () {
posts.push(post);
}, 2000);
}
function getPost() {
setTimeout(function (){
let output = "";
posts.forEach(function (post) {
output += `<li>${post.title}</li>`;
});
document.body.innerHTML = output;
}, 1000);
}
createPost({title: "Post Three", body: "Three"});
getPost();
이 때 Callback function을 이용하여 다음과 같이 포스트를 만들 때 새로 추가된 포스트까지 가져오는 기능을 구현할 수 있다.
...
function createPost(post, callback) {
setTimeout(function () {
posts.push(post);
callback();
}, 2000);
}
...
createPost({title: "Post Three", body: "Three"}, getPost);
'2021 프론트 엔드 로드맵 따라가기 > JS' 카테고리의 다른 글
AJAX POST request (0) | 2021.06.07 |
---|---|
AJAX 이용 시 주의할 점 (0) | 2021.06.07 |
REST API (0) | 2021.06.07 |
XHR object를 이용한 비동기 통신 (0) | 2021.06.07 |
AJAX란 (0) | 2021.06.07 |
Comments