Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // PROMISES
- // Promises for handling asynconist oprations as like callback's
- // Promises is ES6 feachure instead of ballback's
- let 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'},
- {title: 'Post 4', body: 'This is post 4'},
- {title: 'Post 5', body: 'This is post 5'},
- ];
- function createPost(post){
- return new Promise(function (resolve, reject) {
- setTimeout(function() {
- let error = true;
- posts.push(post);
- if (error) {
- reject('Something wrong!');
- } else {
- resolve();
- }
- }, 2000);
- });
- }
- function getPosts() {
- setTimeout(function () {
- let output = '';
- posts.forEach(function (post) {
- output += `<li>${post.title}: ${post.body}</li>`;
- });
- document.body.innerHTML = output;
- }, 1000);
- }
- let post = {
- title: 'Post 6', body: 'This is post 6'
- };
- createPost(post)
- .then(getPosts) // if resolve
- .catch(function (err) { // if reject
- console.log(err);
- });
Add Comment
Please, Sign In to add comment