daily pastebin goal
52%
SHARE
TWEET

Untitled

a guest Aug 14th, 2018 53 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // PROMISES
  2.  
  3. // Promises for handling asynconist oprations as like callback's
  4. // Promises is ES6 feachure instead of ballback's
  5.  
  6.  
  7. let posts = [
  8.     {title: 'Post 1', body: 'This is post 1'},
  9.     {title: 'Post 2', body: 'This is post 2'},
  10.     {title: 'Post 3', body: 'This is post 3'},
  11.     {title: 'Post 4', body: 'This is post 4'},
  12.     {title: 'Post 5', body: 'This is post 5'},
  13. ];
  14.  
  15. function createPost(post){
  16.     return new Promise(function (resolve, reject) {
  17.         setTimeout(function() {
  18.             let error = true;
  19.             posts.push(post);
  20.                 if (error) {
  21.                     reject('Something wrong!');
  22.                 } else {
  23.                     resolve();
  24.                 }
  25.         }, 2000);    
  26.     });
  27. }
  28.  
  29. function getPosts() {
  30.     setTimeout(function () {
  31.         let output = '';
  32.         posts.forEach(function (post) {
  33.             output += `<li>${post.title}: ${post.body}</li>`;
  34.         });
  35.         document.body.innerHTML = output;
  36.     }, 1000);
  37. }
  38.  
  39. let post = {
  40.     title: 'Post 6', body: 'This is post 6'
  41. };
  42.  
  43.  
  44. createPost(post)
  45.     .then(getPosts) // if resolve
  46.     .catch(function (err) { // if reject
  47.         console.log(err);
  48.     });
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top