JavaScript: Promises async/ await

Hello fellow developers, today I will talk about promises using async/ await. In my previous post I have talked about then() and catch() methods. Their use is almost the same, so you can switch in between them in many cases.

I will use our blog example again, so here it is. I will still break it down into pieces to make it easier to digest.

*I assume you know the map() method. If not, please read this

This is where we get our data, mimicking fetching from an API :)

const blogs = [
  { title: "title 1", author: "author 1" },
  { title: "title 2", author: "author 2" },
  { title: "title 3", author: "author 3" },
  { title: "title 4", author: "author 4" },
];

This function lists our data, in this case, blog. The function returns a new Promise. When the promise is fulfilled (resolved) it maps over our list and logs it to the console. Logs only titles and authors of our blog.

The weird code you see with ? and : is the ternary operator. Ternary operator asks if list variable is true. If it is true (gets data), it logs the blogs on the console, else, it displays Cannot list blogs, please try again later.

function listAllBlogs(blogList) {
  return new Promise((resolve, reject) => {
    const list = blogList.map((blog) => console.log(blog.title, blog.author));

    list ? resolve(blogList) : reject("Cannot list blogs, please try again later");
  });
}

Time to use async and await. From the get-go, we tell JavaScript that this is an async function, so it knows it will stay await for something to happen. If something happens, it will run the code in the try block. Why put in try block. Because JavaScript first tries to run that code if it cannot run, it goes to the catch block. So, it will catch the error

async function processBlogs() {
  try {
    await addBlog({ title: "title 12", author: "author 12" }, blogs);
    await listAllBlogs(blogs);
  } catch (err) {
    console.log(err);
  }
}
processBlogs();

That is our program that receives data. Once it has received data, it lists the data. If the user wants to add more data, then it adds more data. That is all for now, keep smiling keep coding