Connor Mills

Connor Mills

1571754664

JavaScript Tutorial: Error handling with Promises and Async/Await

Error handling in JavaScript can be easy while being tricky at certain places, especially Promises. JS allows error handling with the help of try, catch, and throw.

const main = () => {
  try {
    // Do something super crazy
    if (!bakePizza()) {
      throw new Error('Oh no!');
    }
  } catch (error) {
    // That escalated quickly
    handleOvenExplosion();
  }
}

This seems simple enough but gets a little tricky when Promises are involved.

Let’s look at a simple example of a Promise. The following Promise function fetches a list of user profiles from the database, where the result set is resolved by the promise function and the error is rejected.

const userProfileQuery = new Promise((resolve, reject) => {
  connection.query('SELECT * FROM Users', [], (err, result) => {
    if (err) reject({ type: 'SQL', err});
    connection.release();
    resolve(result);
});
userProfileQuery
  .then((data) => {
    const userList = data;
    // Do something crazy with the list
  })
  .catch((err) => {
    // Oh, snap!
    // Handle error
  });

In an ideal world, we’d want to have a single try-catch block to handle all errors that occur in that single file.

const { getUserProfiles } = require('./helpers');
module.exports = () => {
  try {
    let userProfileList;
    getUserProfiles
      .then((data) => {
        userProfileList = data;
      })
      .catch((error) => {
        // Handle Promise Error
        // All errors thrown in this promise land here
      });
  } catch (error) {
    // Handle errors in this module
  }
}

The above module is simple — It fetches a list of user profiles with the help of a Promise function.

But the problem with the above module is that when we throw a new Error inside the then block of the promise, it will always pass to the catch block of the promise. That is because throwing a new error inside a then block of a promise will always be passed to the catch block of the invoking promise function. This does not allow us to handle all errors in a module with a singular try-catch block.

But, alas! There is a way to handle this with the help of Async/Await. Let me explain this better with an example:

const { getUserProfiles } = require('./helpers');
module.exports = async () => {
  try {
    const userProfileList = await getUserProfiles;
  } catch (error) {
    // Handle errors in this module
    switch (type) {
      case ERROR_SQL:
        // Handle SQL errors
      default:
        // Handle common errors
    }
  }
}

This little addition of async/await in your code does two things
Assign the value to the variable which was resolved by the promise function.

Throw error if the promise function rejects anything.
Note that the value assignment works only when a promise functions resolves some value and errors get thrown only when the promise function rejects something.

This way, async/await lets us keep our code clean, maintainable, and easy to read.

Thanks for reading. If you have thoughts on this, be sure to leave a comment.

#javascript #nodejs #node

What is GEEK

Buddha Community

JavaScript Tutorial: Error handling with Promises and Async/Await
Giles  Goodwin

Giles Goodwin

1600929360

Understanding JavaScript: Promises, Async & Await!!

Analogy

We all know the importance of promises in our life. We even have a special day dedicated to it :) But how well do we know the importance of promises in JavaScript? Well if you don’t know it yet, it’s a great time to know it because they are becoming more and more popular. So what are promises? Let’s try to understand it through an analogy.

Suppose you are a top class rapper and you haven’t released an album for a while and fans are asking for it day and night. So what you do is that you “promise” them that whenever it will be out, all of them would be notified. To get this done you give your fans a list. They can fill in their email addresses, so that when the album becomes available, all the subscribers instantly receive it. And even if something goes wrong, say a pandemic, so that you can’t release the album, they will still be notified.

Now everyone is happy: You, because the people don’t crowd you anymore, and fans, because they won’t miss any news on the album.

This is a real-life analogy for things we often have in programming:

  1. “producing code” that does something and may take time. That’s a “rapper”.
  2. “consuming code” that wants the result of the “producing code” once it’s ready. Many functions may need that result. These are the “fans”.
  3. A promise is a special JavaScript object that links the “producing code” and the “consuming code” together. In terms of our analogy: this is the “subscription list”. The “producing code” takes whatever time it needs to produce the promised result, and the “promise” makes that result available to all of the subscribed code when it’s ready.

JavaScript promises are much more complex than a simple subscription list: they have additional features and limitations. But it’s fine to begin with.

#async #promises #javascript #development #await

Julie  Donnelly

Julie Donnelly

1602406920

JavaScript Promise: Methods Comparison

Introduction

Promises in JavaScript are used to handle asynchronous operations by keeping track of whether a certain event has happened. If that certain event has taken place, it determines what happens next. Promises return a value which is either a resolved value or a reason why it’s rejected. They can handle multiple asynchronous operations easily and they provide better error handling than callbacks and events.

Callback: A callback is a function that is passed into another function as an argument to be executed later.

Events: Events provide a dynamic interface to a WebPage and are connected to elements in the Document Object Model(DOM), for example: onclick(), onmouseover() etc.

A Promise has four states

Pending: Before the event has happened, the promise is in the pending state.

Settled: Once the event has happened it is then in the settled state.

Fulfilled: Action related to the promise has succeeded.

Rejected: Action related to the promise has failed.

#javascript #javascript-development #javascript-tutorial #promises #javascript-tips

Terry  Tremblay

Terry Tremblay

1602147513

Now Learn JavaScript Programming Language With Microsoft

icrosoft has released a new series of video tutorials on YouTube for novice programmers to get a hands-on renowned programming language — JavaScript.

This isn’t the first attempt by Microsoft to come up with video tutorials by beginner programmers. The company also has a series of YouTube tutorials on Python for beginners.

For JavaScript, Microsoft has launched a series of 51 videos as ‘Beginner’s Series to JavaScript,’ for young programmers, developers and coders who are interested in building browser applications using JavaScript. These video tutorials will also help programmers and coders to use relevant software development kits (SDKs) and JavaScript frameworks, such as Google’s Angular.


“Learning a new framework or development environment is made even more difficult when you don’t know the programming language,” stated on the Microsoft Developer channel on YouTube. “Fortunately, we’re here to help! We’ve created this series of videos to focus on the core concepts of JavaScript.”

It further stated — while the tutorials don’t cover every aspect of JavaScript, it indeed will help in building a foundation from which one can continue to grow. By the end of this series, Microsoft claims that the novice programmers will be able to work through tutorials, quick starts, books, and other resources, continuing to grow on their own.


#news #javascript #javascript tutorial #javascript tutorials #microsoft tutorials on javascript

wp codevo

wp codevo

1608042336

JavaScript Shopping Cart - Javascript Project for Beginners

https://youtu.be/5B5Hn9VvrVs

#shopping cart javascript #hopping cart with javascript #javascript shopping cart tutorial for beginners #javascript cart project #javascript tutorial #shopping cart

Javascript : Async Await in Javascript | Javascript Interview questions.

Explained in detail about

  • Async
  • Await
  • Fetching country data using Async & Await
  • How Async & Await better than promise

Dont miss to watch the video & ask your questions or doubts in comments

https://youtu.be/pJbsd2vAqdI

#javascript #async #await