Skip to content

Instantly share code, notes, and snippets.

@whal-e3
Created November 14, 2020 10:06
Show Gist options
  • Save whal-e3/8d6f4e882fac49416879e7446c6a8a76 to your computer and use it in GitHub Desktop.
Save whal-e3/8d6f4e882fac49416879e7446c6a8a76 to your computer and use it in GitHub Desktop.
JS es6 Promises
const posts = [
{ title: 'Post one', body: 'this is post one' },
{ title: 'Post two', body: 'this is post two' }
];
function createPost(post) {
return new Promise(function (resolve, reject) {
setTimeout(function () {
posts.push(post);
const error = false;
if (!error) {
resolve();
} else {
reject('error: something went wrong');
}
}, 2000);
});
}
function getPosts() {
setTimeout(function () {
let output = '';
posts.forEach(function (post) {
output += `<li>${post.title}</li>`;
});
document.body.innerHTML = output;
}, 1000);
}
createPost({ title: 'post three', body: 'this is post three' })
.then(getPosts)
.catch(function (err) {
console.log(err);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment