DEV Community

Cover image for Asynchronous JS: Working with try/catch and promises
DevLorenzo
DevLorenzo

Posted on • Updated on

Asynchronous JS: Working with try/catch and promises

Hello World! New episode of the series - A CSS/JS trick in 5 minutes.
Today we will quickly see how to handle errors with javascript. First with try/catch, then with promises.


First, it's important to notice that a majority of backend actions have an unknown result, we don't know if it will work when we write our code. So we always have to write two different codes, one if the action works, another if the action results in an error. This is exactly how a try/catch work, we submit a code to try, if it works code continues, if it doesn't we catch the error (avoiding the app crashing) and run another code. This is a very common thing we don't only use in web development (also in Android app development with java for example).


Try / Catch

  try {
  // Try to run this code 
 // For example make a request to the server
}
catch(e) {
  console.log(e)
  // if any error, Code throws the error
 // For example display an error message to the user
}
Enter fullscreen mode Exit fullscreen mode

Catch provides us a parameter, the error that occurred (we usually name it e, err, or error). We can for example log this error to the console when we are in a testing phase or we can save it (maybe in a database with a list of errors).

We can also have (but it far less common) another part, called finally. It's a code that will always be executed after your try/catch.

 finally {
  // Always run this code regardless of error or not
  // This block is optional
}
Enter fullscreen mode Exit fullscreen mode

Promises

The big problem with try/catch is that when you have to nest it (and you will have), it's really messy and difficult to read and write. So Javascript support promises with async functions:

Syntax: new Promise (executor)
executor= (accept, reject) =>{}

var asyncronus_function = (number)=>
        {
            return new Promise( (accept, reject)=>
            {
            })
        } 
Enter fullscreen mode Exit fullscreen mode

This function returns a promise object.
If function end well we return a accept(), otherwise reject()

Another asyncronus_function example:

var asyncronus_function = (number)=>
        {
            return new Promise( (accept, reject)=>
            {
                if(number>10)
                return accept("my first async");
                return reject("my first async error")
            })

        }
Enter fullscreen mode Exit fullscreen mode

if it doesn't return any of these 2 function, Promise state is [PENDING], if return accept is [RESOLVED] and if return reject is [REJECTED]

Then we can add a code if it works and another if it doesn't:

1) .then(function(error){}) is call when promise state is [RESOLVED]
2) .error(function(error){}) is call when promise state is [REJECTED]
3) Do nothing if [PENDING]

Then we call asyncronus_function():

    asyncronus_function(number).then(function(data)
        {
            console.log(data)
        }).catch(error => 
        {
                console.log(error)
        });
Enter fullscreen mode Exit fullscreen mode

Hope this helped and thanks for reading!

Please smash that like button to make me understand that you want the series to continue :)

Check this article about how to write CSS like a pro!

Discussion (0)