DEV Community 👩‍💻👨‍💻

Naveen Dinushka
Naveen Dinushka

Posted on

Async JS - Callbacks, Promises, Async await

Disclaimer: This post is based on the video and Joys icecream post

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(){
  let output ='';
     output +=`<li> ${post.title},</li>';
  document.body.innerHTML = output;},1000);
function createPost (post ){

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


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) {
 //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(()=> {

      const error = false;

      } else {
       reject('Error: something went wrong');

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('').then(res=>res.json());

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'});

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 ('');

const data = await res.json()



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)=>{

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


async function kitchen(){


  await toppings_choice()



// Trigger the function

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

doing the dishes
cleaning the tables
taking orders
which topping would you love
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)

Visualizing Promises and Async/Await 🤯

async await

☝️ Check out this all-time classic DEV post