martes, 26 de octubre de 2021

Javascript async/await

 Javascript async/await

using async await , we use a promise in createPost(post) an asynchronous process that add a post retarded by 200 millisecond, so the getPost() process before and It would not be aware of the update thanks to the async-await that waits the execution of the getPosts() process until the createPost finishes the posts update.


const posts = [{title: 'post one', body: 'body of post one'},
              {title: 'post two', body: 'body of post two'}];

function getPosts(){
  setTimeout(() => {
      let output = '';
      posts.forEach( (post, index) => {
        console.log(index + ' ' + post.title );
        output += `<li>${post.title}</li>`;
      });
      document.body.innerHTML = output;
  }, 100);
};

function createPost(post){
   return new Promise((resolve,reject) => {
      setTimeout(() => {
        posts.push(post);
        resolve();
      }, 200)
   })
};

async function processPost(){
   await createPost({title: 'post three', body:'body of post three'});
   getPosts();
}

processPost();

 
browser output:
  • post one
  • post two
  • post three
  •  
    with out the async / await code
     
    browser output:
  • post one
  • post two
  •  
    this is because the getpost() process run before posts are updated with the third record.
     
    async function fetchUser(){
       const res = await fetch('https://jsonplaceholder.typicode.com/users');
       const data = await res.json();
       console.log(data);
    }

    fetchUser();

     
    browser inspector output:

    XHR GEThttps://jsonplaceholder.typicode.com/users
    Array(10) [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…} ]
    0: Object { id: 1, name: "Leanne Graham", username: "Bret", … }
    1: Object { id: 2, name: "Ervin Howell", username: "Antonette", … }
    2: Object { id: 3, name: "Clementine Bauch", username: "Samantha", … }
    3: Object { id: 4, name: "Patricia Lebsack", username: "Karianne", … }
    4: Object { id: 5, name: "Chelsey Dietrich", username: "Kamren", … }
    5: Object { id: 6, name: "Mrs. Dennis Schulist", username: "Leopoldo_Corkery", … }
    6: Object { id: 7, name: "Kurtis Weissnat", username: "Elwyn.Skiles", … }
    7: Object { id: 8, name: "Nicholas Runolfsdottir V", username: "Maxime_Nienow", … }
    8: Object { id: 9, name: "Glenna Reichert", username: "Delphine", … }
    9: Object { id: 10, name: "Clementina DuBuque", username: "Moriah.Stanton", … }
    length: 10

     
    eot

    No hay comentarios:

    Publicar un comentario