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

How can I generate a bounding box with CSS?

I am a newcomer to vue.js and I have a question about creating a bounding box for any element. This bounding box resembles a view box in svg. For example, I have created a checkbox like this one: checkbox Below is the code to style the checkbox: /* checkb ...

I am experiencing difficulty in successfully transmitting a variable from my jQuery code to my PHP code

I've been attempting to pass a variable from my jQuery code to my HTML/PHP code using AJAX and POST. However, I'm encountering an error message stating "Notice: Undefined index: testData in C:\xampp\htdocs\teszt\test1.php on l ...

What is the process for generating a collection of objects in a Mongoose Model?

I am currently working on creating a structure similar to this: var User = mongoose.model('Clicker', totalClicks: [ {type: Number, default: 0}, {type: Number, default: 0} ], I have explored various documentation resources related to ...

Encountering a problem where updating the selected option in a dropdown does not properly refresh the HTML

I am currently working with a dropdown menu containing countries. Initially, the selected item is set to Ukraine. <select id="country" name="country"> <option value="US">USA</option> <option value="UG">Uganda</option> ...

Create original identifiers for dynamically generated material

I have developed a custom invoice tool that has the capability to dynamically add rows. Here is the code snippet responsible for generating new rows: $("#addrow").click(function(){ $(".item-row:last").after('<tr class="item-row"><td> ...

A guide on how to identify the return type of a callback function in TypeScript

Looking at this function I've created function computedLastOf<T>(cb: () => T[]) : Readonly<Ref<T | undefined>> { return computed(() => { const collection = cb(); return collection[collection.length - 1]; }); } Thi ...

The Vue js post request encountered an issue due to the absence of the CSRF token

When attempting to make a post request, an error message indicates that the CSRF token is missing. I am using Vue.js and DRF - how can I properly pass the CSRF token in Vue? function(){ this.loading = true; this.$http.post('/get_books/&apos ...

Error: Attempted to update user profile with an invalid function in Firebase

After creating an Avatar Chooser, I am encountering an error when selecting an image. Instead of displaying the selected image in the avatar, the error message is being displayed. How can I resolve this and ensure that the image appears in the Avatar Icon ...

Is there an issue with VUE npm run serve due to Tailwindcss being absent?

A few months back, I embarked on a project using Vue and incorporated Tailwind CSS by running the command (Vue add Tailwind). Recently, when attempting to create a new project with the default Vue3 template using the command vue create project and then na ...

Convert JavaScript back into an HTML attribute

Is there a way to include a JavaScript code in an HTML attribute like shown below? <div class="xx" animation="yy" animate-duration="<script>Code goes here<script>" ...> </div> I'm struggling to figure it out, is there a solut ...

Issue: Unable to locate the module 'nexmo' & error TS2307: 'nexmo' module not found

Currently, I am utilizing the powerful NestJs Framework alongside typescript. My task involves incorporating two-factor authentication (SMS) using the Nexmo node library. You can find further information on their website: During the development phase, ev ...

Sliding multiple divs up and down with jQuery

Here is the code that I am working with: JavaScript: $(".Head").click(function () { if ($(".Body").is(":hidden")) { $(".Body").slideDown('fast'); } else { $(".Body").slideUp('fast'); } }); HTML: ...

Having trouble accessing NWJS modules with your new windows?

When I create a window using window.open in my NWJS application, it appears that the window is unable to access any nodejs or nwjs modules. How can I find a solution for this issue? I utilize document.write to add content to the page because the content m ...

Is there a way to incorporate a responsive side menu using JQuery or CSS3 that can shift the entire page layout?

Hey there, I'm currently trying to incorporate a responsive side menu into my website using either JQuery or CSS3. What I need is a side menu that will smoothly shift the page content when a link is clicked, and also adds a close button (X) to the men ...

A guide on harnessing the power of Jest when integrating it with vuex-module-decor

In my Typescript-written Vue component, I am facing an issue while trying to write a unit test using vue-test-utils and jest. The problem arises when injecting the vuex store that was created with vuex-module-decorators. Below is a snippet from my Vue com ...

Conceal virtual keyboard on mobile when in autocomplete box focus

I would like the keyboard to remain hidden when the autocomplete box is focused or clicked, and only appear when I start typing. The code below currently hides the keyboard when any alphabets or numbers are pressed. However, I want the keyboard to be hidd ...

The connections between children in the Highcharts Org chart are getting tangled up

I am facing an issue with the organization chart I created using highcharts. Specifically, at the 3rd level, the links are becoming merged or overlapped with other child links. The data for the chart is being sourced from an ERP system and contains informa ...

What are the appropriate scenarios to utilize the declare keyword in TypeScript?

What is the necessity of using declare in TypeScript for declaring variables and functions, and when is it not required? For instance, why use declare var foo: number; when let foo: number; seems to achieve the same result (declaring a variable named ...

422 Update Error when making changes in the modal using axios.put [laravel and vuejs 3]

I am currently working on a project using Laravel and VueJS 3, For updating details of a single user in a table row via a modal, I am utilizing the axios.put method. However, I am encountering issues when trying to submit the form inside the modal using a ...

Ways to retrieve the state within a mapping array

I am currently facing an issue that I need assistance with: this.state.renderMap.map(function(name, index) { return ( <View style={styles.checkBoxWrapper} key={index}> <CheckBox title={name} value={() => {this.state.nam ...