Ember.js is an open-source JavaScript framework used for developing large client-side web applications which are based on Model-View-Controller (MVC) architecture. Ember.js is one of the most widely used front-end application frameworks. It is made to speed up development and increase productivity. Currently, it is utilized by a large number of websites, including Square, Discourse, Groupon, Linked In, Live Nation, Twitch, and Chipotle.
The catch() method is used to handle rejected promises.
Syntax:
catch(onRejected, String label)
Parameters: It takes two parameters.
- Onrejected: This is a callback back function that is executed when the promise is rejected.
- String label: This is used to label the promise, this is basically an optional parameter.
Return Value: It returns a new promise.
Steps to Install and Run Ember.js:
Step 1: To run the following examples you will need to have an ember project with you. To create one, you will need to install ember-cli first. Write the below code in the terminal:
npm install -g ember-cli
Step 2: Now you can create the project by typing in the following piece of code:
ember new <project-name> --lang en
Step 3: To start the server, type:
ember serve
Step 4: After the above query is executed successfully you can check your progress on
http://localhost:4200/
Example 1: Type the following code to use the catch() method to catch the error generated by the reject() method.
app/controller/app.js
Javascript
const Promise1 = new Promise((resolve, reject) => { setTimeout( function () { Math.random() == 0.5 ? resolve( 'Success!' ) : reject( new Error( 'Something went wrong' )); }, 1000); }); Promise1 .then((result) => { console.log(result); }) . catch (() => { console.log( 'Error has Occurred' ); }); |
app/templates/application.hbs
Javascript
{{page-title "Emberjs" }} <div> <h2> Welcome to the tutorial of Promises in Ember.js </h2> </div> |
Output: Visit localhost:4200/ to view the output
Example 2: Type the following code to use the catch() method to catch the error generated by the reject() method.
apps/controller/app1.js
Javascript
let promise2 = new Promise((resolve, reject) => { console.log( 'Promise 2' ); setTimeout(() => { const a = 5; a >= 18 ? resolve( 'Success!' ) : reject( new Error( 'something has occurred' )); }, 2000); }); promise2 .then((result) => { console.log(result); }) . catch (() => { console.log( 'Error has Occurred' ); }); |
app/templates/application.hbs
Javascript
{{page-title "Emberjs" }} <div> <h2>Welcome to the tutorial of Promises in Ember.js </h2> </div> |
Output: Visit localhost:4200/ to view the output
Reference: https://api.emberjs.com/ember/3.18/classes/Promise/methods/catch?anchor=catch