Skip to content

Instantly share code, notes, and snippets.

@HelloAlberuni
Created June 17, 2021 13:31
Show Gist options
  • Save HelloAlberuni/762ef8cd3784cff0624800d867ec8b17 to your computer and use it in GitHub Desktop.
Save HelloAlberuni/762ef8cd3784cff0624800d867ec8b17 to your computer and use it in GitHub Desktop.
Practice JS Promise
const posts = [
{title: 'Post 1', body: 'this is post 1'},
{title: 'Post 2', body: 'this is post 2'},
{title: 'Post 3', body: 'this is post 3'},
];
// Callback way
// function createPost(post, callback){
// setTimeout(function(){
// posts.push(post);
// callback();
// }, 2000);
// }
// function getPosts(){
// setTimeout(function(){
// let output = '';
// posts.forEach(function(post){
// output += `<li>${post.title}</li>`;
// });
// document.body.innerHTML = output;
// }, 1000);
// }
// createPost({title: 'Post 4', body: 'this is post 4'}, getPosts);
// Promise way (promise is better than using callback)
function createPost(post){
return new Promise(function(resolve, reject){
setTimeout(function(){
posts.push(post);
let err = false;
if( !err ){
resolve();
} else {
reject('Something went wrong!');
}
resolve();
}, 2000);
});
}
function getPosts(){
setTimeout(function(){
let output = '';
posts.forEach(function(post){
output += `<li>${post.title}</li>`;
});
document.body.innerHTML = output;
}, 1000);
}
createPost({title: 'Post 4', body: 'this is post 4'})
.then(getPosts)
.catch(function(response){
document.body.innerHTML = response;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment