카테고리 없음
[Javascript] 비동기 JS Callbacks, Promises, Async Await
Gilvert
2018. 7. 1. 23:14
728x90
#1. callback
const posts = [{
title: 'post1',
body: 'this is one'
},
{
title: 'post2',
body: 'this is two'
}
]
function getPosts() {
setTimeout(() => {
let output = '';
posts.forEach((post, index) => {
output += '<li>$post.tilte</li>';
});
document.body.innerHTML = output;
}, 1000);
}
#2. promise
- 참고 사이트: https://joshua1988.github.io/web-development/javascript/promise-for-beginners/
- 사용이유:
function createPost(post, callback) {
return new Promise((resolve, reject) =>{
setTimeout(() => {
posts.push(post);
const error = false;
if(!error){
resolve();
}else{
reject('Error message: youngsu');
}
}, 2000);
});
}
const promise1 = Promise.resolve('hello gilyoungsu');
const promise2 = 10;
const promise3 = new Promise((resolve,reject) =>
setTimeout(resolve, 2000, 'gilyoungsu1'));
const promise4 = fetch('https://jsonplaceholder.typicode.com/users').then(res =>
res.json());
Promise.all([promise1,promise2,promise3,promise4]).then(values => console.log(values),promise4)
#3. async, awit
async function fetchUsers(){
const res = await fetch('https://jsonplaceholder.typicode.com/users');
const data = await res.json();
console.log(data);
}
#4. 기타
참고사이트
더미 json 파일 모음
https://jsonplaceholder.typicode.com/users

"파트너스 활동을 통해 일정액의 수수료를 제공받을 수 있음"