Created
November 14, 2020 10:06
-
-
Save whal-e3/8d6f4e882fac49416879e7446c6a8a76 to your computer and use it in GitHub Desktop.
JS es6 Promises
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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