DEV Community

Naveen Dinushka
Naveen Dinushka

Posted on

Async JS - Callbacks, Promises, Async await

Disclaimer: This post is based on the video https://www.youtube.com/watch?v=PoRJizFvM7s&t=23s and Joys icecream post https://dev.to/joyshaheb/learn-callbacks-promises-async-await-by-making-ice-cream-4n76

Look at the below code snippet and answer the questions

const posts =[
{title:'post one', body:'This post one'},
{title:'post two',body:'This is post two'}
]
function getPosts(){
  setTimeout(()=>{
  let output ='';
  posts.forEach((post,index)=>{
     output +=`<li> ${post.title},</li>';
});
  document.body.innerHTML = output;},1000);
}
function createPost (post ){
  setTimeout(()=>{
   posts.push(post);

  },2000);
}
getPosts()
createPost({title:'Post Three', body:'This is post three'} );
Enter fullscreen mode Exit fullscreen mode

Questions

1. What would happen if we run the above code? Explain?

We would only see post one and post two printed, we cant get the post three printed as create Post has a delay of 2 seconds and by the time CreatePost is run (in 2 sec) the getPosts function had already completed its execution

2. How can we fix the above, and print three posts by amending the above code snippet?

We can do this by amending the code snippet to call the getposts function inside createPosts , to do this we have to add getPosts function inside createPost, and add a callback as below

function createPost(post,callback) {
 setTimeout(()=>{
  posts.push(post);
 callback();
},2000);
}
 //and then

createPost({title:'Post three', body: 'This is post three'}, getPosts);
Enter fullscreen mode Exit fullscreen mode

3. Using the amended code in (2) above, perform the same with promises instead of callbacks.

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

      const error = false;

      if(!error){
       resolve();
      } else {
       reject('Error: something went wrong');
    }
},2000);
});
}

createPost({title:'Post three', body:'This is post three'}).then(getPosts).catch(err=> console.log(err));
Enter fullscreen mode Exit fullscreen mode

4. Whats the use of promise.all?

If we have lot of different promises, instead of writing a lot of .then promises we can do promise.all , as below

const promise1 = Promise.resolve('Hellow world')
const promise2 = 10;
const promise3 = new Promise((resolve, reject)=>setTimeout(resolve,2000,'Goodbye'))
const promise4=fetch('https://jsonplaceholder.typicode.com/users').then(res=>res.json());


Promise.all([promise1,promise2,promise3,promise4]).then(
(value)=>console.log(values)
);
Enter fullscreen mode Exit fullscreen mode

5. What is the use of 'async , await' in the context of promises, use async, await to print three posts, 2 from the posts abject , and one manually added, with createPost and getPosts functions.

Example 1

async function init(){

  await createPost({title:'Post three', body:'This is post three'});
  getPosts()
}

init()
Enter fullscreen mode Exit fullscreen mode

so you would see all three posts in the output of the above code, because with the await keyword the createPost would finalize executing before it goes to getPosts()

Example 2 with fetch

async function fetchUsers(){
  const res = await fetch ('https://jsonplaceholder.typicode.com/users');

const data = await res.json()

console.log(data);

}

fetchUsers();
Enter fullscreen mode Exit fullscreen mode

6. Answer the questions based on the program written using async await

function toppings_choice (){
  return new Promise((resolve,reject)=>{
    setTimeout(()=>{

      resolve( console.log("which topping would you love?") )

    },3000)
  })
}

async function kitchen(){

  console.log("A")
  console.log("B")
  console.log("C")

  await toppings_choice()

  console.log("D")
  console.log("E")

}

// Trigger the function

kitchen();
console.log("doing the dishes")
console.log("cleaning the tables")
console.log("taking orders")

Enter fullscreen mode Exit fullscreen mode

a. What would be the output and why

The out put of this would look like

output
A
B
C
doing the dishes
cleaning the tables
taking orders
which topping would you love
D
E
Enter fullscreen mode Exit fullscreen mode

This is because execution of kitchen function was paused at toppings_choice() and other console.logs were executed while toppings_choice() was executing in the background and then the rest of the lines in the kitchen function .

b. Whats the key difference between getPosts example and this example?

In the getPosts example the async function we used was init(), it had one promise inside with await keyword, the execution paused at 'CreatePosts' function until it finished executing, however in this example we have multiple functions , which are console.logs, the await function is paused inside the kitchen function while the console.logs outside of the kitchen function are executed.

Top comments (0)