What is the significance of using a double arrow function in Javascript?

Can someone explain the double arrow notation used in the code snippet below? How does the second arrow function get executed if the first one's response is true? And in what scenarios is this notation typically used?

  async check({ commit }) {
     await axios.get('check')
     .then((response) => {
      console.log("try");
     }, (response) => {
      console.log("try2");
     }

     return true;
     });

Answer №1

Arrow functions are not relevant here. The key point is the then method on promises.

When using a promise's then method, the first argument serves as a fulfillment handler while the second acts as a rejection handler. If the promise is fulfilled, the fulfillment value is passed to the first handler. On the other hand, if the promise is rejected, the rejection reason is passed to the second handler. Only one of these handlers will be called for a given promise, never both simultaneously.

Below is an updated snippet of the function referenced earlier in the question, featuring modified names and the removal of return true;, which was unclear in its placement:

async check({ commit }) {
    await axios.get('check')
    .then(
        (value) => {                       // ***
            // Process the fulfillment value  // *** fulfillment handler
        },                                 // ***

        (reason) => {                      // ***
            // Handle the rejection           // *** rejection handler
        }                                  // ***
    );
});

For more information on promises, refer to the resources on MDN or the Promises A+ specification that underpins JavaScript's promise implementation.


It should be noted that making this specific function an async function may not be necessary unless the intention is specifically to conceal any fulfillment values or rejection reasons provided by the promise handler. However, this approach achieves that, so it could serve a particular purpose in this context.

Answer №2

The Promises/A+ guideline specifies that then can accept two parameters:

promise.then(onFulfilled, onRejected)

The second parameter is the onRejected handler.

Although it may not be as commonly used with catch() available, it remains a part of the standard.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Google Chrome console is failing to display the accurate line numbers for JavaScript errors

Currently, I find myself grappling with debugging in an angular project built with ionic framework. Utilizing ion-router-outlet, I attempt to troubleshoot using the Google Chrome console. Unfortunately, the console is displaying inaccurate line numbers mak ...

"Troubleshooting HTTP requests in Angular: Dealing with

I encountered an issue while attempting to test an http request with a dynamic URL. Within my service file, I have the following snippet: Snippet from My Service File: //other service codes.. //other service codes.. var id = $cookies.id; return $http.ge ...

IE11/Edge exhibits slow performance with components that have large datasets exclusively

Take a moment to analyze the following code snippet: <GridBody Rows={rows} />. Let's say that in this scenario, rows.length could reach 2000 or more, with each array containing approximately 8 columns. I have encountered a performance bottleneck ...

Utilizing HTML5 to automatically refresh the page upon a change in geolocation

I have a web application built with AngularJS. One of the functionalities is activated only when the user is in close proximity to specific locations. To make this work, I can constantly refresh the page every 5 seconds and carry out calculations to dete ...

What is the best way to handle JSON data errors when a value is undefined?

I am currently working on a piece of code that displays JSON data in HTML. However, if a value is undefined, it doesn't display anything. How can I handle this error so that if a value is undefined, it will show "N/A" instead of breaking the code? ...

(Enhancing Angular) Capture HttpResponse errors and seamlessly proceed with the Observable

There's a dropdown text box with type-ahead search functionality. Valid item names prompt the expected list of items in the drop-down menu, while invalid entries trigger a 400 error response from the API. This error is caught by the HttpErrorIntercept ...

The error message "TypeError: Cannot set property 'href' of undefined" occurred at angular.js line 12520 when trying to set $window.location.href

Has anyone tried using a directive function to redirect when clicking with ng-click? Here is the HTML code: <a ng-click="navbarlinksCtrl.clickedfr()" ng-class="{active: clickedfr()}">FR</a><br> <a ng-click="navbarlinksCtrl.clickeden( ...

One way to change the cursor CSS property is by dynamically altering it based on scrolling behavior. This involves modifying the cursor property when scrolling

I'm attempting to adjust the cursor property within an Angular function. The issue I'm facing is that when I begin scrolling the webpage, the cursor changes to a pointer, but when I stop scrolling, it remains as a pointer. I've attempted to ...

The custom pagination feature in Addsearch UI always default to displaying the first page of search

I am currently using addsearch-ui version 0.7.11 for my project. I have been attempting to integrate a customized pagination function based on this example template. However, I have encountered an issue where the arrow buttons always navigate to the first ...

After combining two files in browserify, the error message "XXX.foo is not a function" appeared

When using browserify to bundle two JavaScipt files into one with the command: browserify X1.js X2.js --standalone XXX > bundle.js The file X1.js contains a function like this: function foo() { console.log("something") } And it is being exported i ...

Press a button to activate a function on a dynamically created table using Ajax

On my website, I have an ajax function that dynamically generates a table and displays it inside a designated div. Below is the PHP code called by the Ajax function. echo "<table border='1' cellspacing='12' cellpadding='4' ...

There was a problem compiling the template and an error occurred in the mounted hook

I am encountering a slight issue with testing Vuejs and I am unsure how to resolve the error. Error1: "[Vue warn]: Error compiling template: Component template should contain only one root element. If you are using v-if on multiple elements, use v-e ...

Prevent background music from being manipulated

I've implemented an audio HTML element with background music for a game: <audio class="music" src="..." loop></audio> However, I have encountered an issue where upon loading the page, I am able to control the music usi ...

In React and Editor.js, the forEach method in the If/Else statement is successfully adding paragraphs but not headlines. Interestingly, this issue seems to be isolated

Looking for assistance with rebuilding my dashboard to React in order to use Editor.js for blog content instead of a textarea. Currently using Editor JS as the editor. On my local machine, everything is working perfectly. I write an article, click Create ...

Can someone explain how to use JavaScript to make table data fill the entire row in a table?

After clicking the button, the layout of the table changes. I want to keep the original table layout even after the JavaScript function runs. I am still learning about JavaScript. function toggle(button) { if(document.getElementById("1").value=="Show ...

Can someone help me figure out this lengthy React error coming from Material UI?

Issues encountered:X ERROR in ./src/Pages/Crypto_transactions.js 184:35-43 The export 'default' (imported as 'DataGrid') could not be found in '@material-ui/data-grid' (potential exports include: DATA_GRID_PROPTYPES, DEFAULT ...

Data within object not recognized by TableCell Material UI element

I am currently facing an issue where the content of an object is not being displayed within the Material UI component TableCell. Interestingly, I have used the same approach with the Title component and it shows the content without any problems. function ...

Allow users to zoom in and out on a specific section of the website similar to how it works on Google Maps

I am looking to implement a feature on my website similar to Google Maps. I want the top bar and side bars to remain fixed regardless of scrolling, whether using the normal scroll wheel or CTRL + scroll wheel. However, I would like the central part of the ...

Searching through a JSON object for nested objects within objects

Currently, I have some data structured as follows: var items = [ { "id" : 1, "title" : "this", "groups" : [ {"id" : 1, "name" : "groupA"}, {"id" : 2, "name" : "groupB"} ] }, { "id" : 2, "title" : "that", ...

Classic design of the shadow element

I have main.js and index.html below class CustomTagA extends HTMLElement { constructor() { super(); const shadow = this.attachShadow({mode: 'open'}); const wrapper = document.createElement('h1'); ...