Promise in JavaScript? How to use Promise?

Tram Ho

Promises are used to handle asynchronous operations in JavaScript. They are easy to manage when dealing with many asynchronous operations where callback statements can generate callback-hell resulting in unmanageable code.

Before the Promise event, callback functions were used a lot, but they had limited functionality and produced unmanageable code. Multiple nested callback functions create callback hell that leads to unmanageable code. Events do not handle asynchronous activities well.

Promise is the ideal choice for the simplest handling of asynchronous operations. They can handle many asynchronous operations with ease and provide better error handling capabilities for function callbacks and events .

  • Promises’ benefits:
    1. Help the callback function become more obvious
    2. Good handling of asynchronous activities
    3. Better definition of processing threads in asynchronous operations
    4. Error handling is better
  • Promises status:
    1. fulfilled : processing involved when the promise was successful
    2. rejected : The handle involved when the promise has failed
    3. pending : The pending Promise, ie no fulfilled or rejected
    4. settled : Promise was fulfilled or rejected
  • A Promise can be created by using the Promise constructor
  • Parameters
    • The Promise constructor takes only one argument as a callback function.
    • The callback function accepts two arguments, resolve and reject.
    • Do things inside the callback function, and if everything goes well, call resolve.
    • If the desired operation fails, call reject.

    Here is an example:

    Output

  • Promise is used like? Promises can be used using the .then and .catch methods.1.then ()
    • then () is called when the promise returns to be resolved or rejected.Parameters:

      The .then () method takes two functions as parameters.

      • The first function is executed if the promise is resolved and gets the result.
      • The second function is executed if the promise is rejected and received an error. (There is a better way to fix the error using the .catch () method)

      About the syntax:

      Promise Rejected Example:

      Output

      Promise Rejected Example:

      Output

    2. catch ()

    • catch () is called when the promise rejects or an error occurs on execution.Parameters:

      catch () takes a function as an argument. It’s the error handling function or a reject promise.

      Execution syntax:

      Promise Rejected Example

      Output

      Or is:

      Output

So how is Promise applied?

  • That’s when you want to handle asynchronous events.
  • It’s a good solution to avoid callback hell .
Share the news now

Source : Viblo