Promise
HTML
<ul id="posts"></ul>
JavaScript
const posts = [
{ title: 'Post One', body: 'This is post one' },
{ title: 'Post Two', body: 'This is post two' }
];
function createPost(post) {
return new Promise((resolve, reject) => {
setTimeout(() => {
posts.push(post);
const error = false;
if (!error) {
resolve();
} else {
reject('Error: Something went wrong');
}
}, 2000);
});
}
function getPosts() {
setTimeout(() => {
let output = '';
posts.forEach((post, index) => {
output += `<li>${post.title}</li>`;
});
document.getElementById('posts').innerHTML = output;
}, 1000);
}
createPost({ title: 'Post Three', body: 'This is post three' })
.then(getPosts)
.catch(err => console.log(err));
Code from Brad Traversy's tutorial:
Async JS Crash Course - Callbacks, Promises, Async Await
https://www.youtube.com/watch?v=PoRJizFvM7s
Demo
Promise using .catch
new Promise((resolve, reject) => {
console.log('Initial');
resolve();
})
.then(() => {
throw new Error('Something failed');
console.log('Do this');
})
.catch(() => {
console.error('Do that');
})
.then(() => {
console.log('Do this, no matter what happened before');
});
MDN Web Docs
Using Promises
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises