How to use axios to retrieve a boolean value

Struggling with obtaining a boolean result using axios in VueJS.

allContactsSaved() {
    let promise = axios.get('/contacts');
    console.log(promise.then(function (response) {
        response.data.data.forEach(function(contact) {
          if (!contact.saved) {
            return false;
          }
        });
        return true;
    }));
  }

The console.log output appears as:

Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}

However, the desired outcome is to obtain either true or false.

Answer №1

It seems like the issue is not related to VueJS or Axios, but rather a misunderstanding of Promises.

Your function operates asynchronously and utilizes Promises to resolve the problem, along with axios.

In order to have allContactsSaved() return true/false for later use, there are 3 options available:

1. Promises

Return a promise and utilize .then when allContactsSaved is invoked, as shown below:

// Function
// Returns promise
allContactsSaved() {
    let promise = axios.get('/contacts').then(function (response) {
        // check if every one is saved
        const check = response.data.data.every(function(contact) {
            return contact.saved;
        });
        return check;
    }));
    return promise;
}

// Implementing it:
allContactsSaved().then(function(isSaved) {
    console.log(isSaved);
});

2. Callbacks

The first option might be preferable over this approach, which is more traditional.

// Function
// Returns promise
allContactsSaved(callback) {
    axios.get('/contacts').then(function (response) {
        // check if every one is saved
        const check = response.data.data.every(function(contact) {
            return contact.saved;
        });
        if(callback) {
            callback(check);
        }
    }));
}

// Using it with a callback function:
allContactsSaved(function(isSaved) {
    console.log(isSaved);
});

3. Async/await

This method is newer in ES6/7 and requires a transpiler depending on the JS engine version.

// Function
// Returns promise
async allContactsSaved() {
    const resp = await axios.get('/contacts');
    const check = response.data.data.every(function(contact) {
        return contact.saved;
    });
    return check;
}

// Utilizing it, the calling function needs to be async:
async function() {
    const result = await allContactsSaved();
    console.log(result);
}

Answer №2

If you want to ensure that all your contacts are saved, you can utilize the every function.

return response.data.every(contact => contact.saved)

Keep in mind that this will still result in a promise being returned. You can continue by chaining another promise:

allContactsSaved() {
let promise = axios.get('/contacts');
promise.then(function (response) {
    return response.data.every(contact => contact.saved)
}).then((areTheySaved) => {
    console.log(areTheySaved);
});

}

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

Retrieving images from a server via AJAX requests

As I delve into learning AJAX, I encountered an issue with retrieving an image from my WAMPSERVER www.directory. Within the IMAGES file, there is an image titled logo.png that I'm attempting to access using the following code: function loadXMLDoc() { ...

Utilizing $setViewValue in Angular 1.4 for Input Date Fields

When using a basic input date field: <form name="form"> <input type="date" name="startDate" my-directive......... To unit test the corresponding myDirective, I am injecting values into the input using $setViewValue. I have decided to use $ ...

"Discover the steps to efficiently utilize the lookup feature with array objects in MongoDB

I am a beginner with MongoDB and I am trying to create a schema for my collection as shown below please note that all ObjectId values are placeholders and not real stockIn documents { serial:"stk0001", date:'2021-06-11', productInTra ...

Add styling to a window popup and close it when focus is lost in Ext JS

I am trying to implement a specific functionality where the popup arrow should be at the edge of the textbox as shown in the image below. How can I achieve this? Additionally, how can I make sure that clicking outside the control destroys the popup instead ...

Creating a Gmail share button in AngularJS: A step-by-step guide

I created a messaging web application using AngularJS, and I successfully added functionality to share messages via email using the "mailto" link. However, this method only works if the user has an email client installed. Now, I am looking for a solution ...

Encountered an Angular SSR error stating "ReferenceError: Swiper is not defined"

When attempting to implement SSR (Server-Side Rendering) in a new project, everything runs smoothly and without issue. However, encountering an error arises when trying to integrate SSR into an existing project. https://i.sstatic.net/QOI6A.png ...

mentioning characteristics that have not been established

In my current project, I am dealing with an array of objects where the properties referenced require examination. The challenge is that these properties are optional and may not always be passed, resulting in errors. Here is a simplified version of the co ...

A guide on effectively utilizing the Map datatype in JavaScript

Recently, I've started delving into the world of es6 Map due to its unique features, but I have some reservations regarding pure operations. For example, when removing properties from objects, I usually use the following function: function cloneOmit ...

Issue with Signature Pad feature "Type It" function not functioning as expected

I am currently experimenting with this GitHub repository. The "Draw It" feature is functioning as expected, however the "Type It" functionality does not populate any value in my hidden input field. Please review the VF page code and screenshot below for f ...

Automatically close the v-autocomplete dropdown after making a selection

I am currently using the vuetify v-autocomplete component and I am trying to make the dropdown close automatically after each selection or deselection. Here is the code snippet that I have implemented: <v-autocomplete v-model="ddselect" :items="ddi ...

Small preview images that open up to larger images in a modal window, with AVIF format displayed first before

On my old website, I have a collection of images displayed in thumbnail form that users can click on to view larger versions. These images are scattered throughout the page and are not the main focus. I'm looking to update this functionality by conve ...

The Ajax call is successful, however, there is no update made to the database

I am currently working on a JavaScript script to allow for profile editing without having to reload the page, similar to how it was done on Facebook. However, I am facing an issue where the AJAX function returns success but does not make any changes in the ...

css: labeling printed pages in Chrome

I need to make sure my project works on Chrome since I am using electron, so using any other browser is not an option. After searching for a solution to this issue without success, I attempted the following approach (taken from CSS page x of y for @media ...

Execute a node script file at random intervals

I've been utilizing forever to maintain the continuous execution of a node script: forever start script1.js However, my requirement is to run these files in a random order... For instance: Execute node script1.js Execute node script2.js Run script ...

Conceal shortcodes in Wordpress's TinyMCE editor

Would it be possible to customize the appearance of shortcodes in the WordPress TinyMCE editor? One of my clients lacks HTML knowledge, making it difficult to explain what should not be edited on subpages. All I am looking for is a way to hide the shortco ...

Removing data from database with ajax

I am encountering an issue with deleting records from my database using ajax and jquery. When I click the button, nothing happens. Here is the relevant css code: <button class='delete_p' id_p='<?php echo $post_id; ?>'>x< ...

A guide to adding and removing classes with a click event in React

Is there a way to dynamically apply and remove CSS classes on click of multiple div elements (rendered by an array of items) in React? <div onClick={() => { toggleActiveClass(`div${index}`) }} className={(activeDiv === `div${index}`) ? "a ...

Trouble with Converting Array Elements into a Div Tag

Could you please review this code and let me know why I am having trouble adding the array items to the .box element? I have tried using both .text() and .html(). var letters = []; var str = "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z"; letters ...

"Using PHP functionality based on the output of a JavaScript function

I'm currently working on a php/html page that involves implementing some javascript functions. My goal is to execute an INSERT query in my MySQL Database only if the result of one of my javascript functions returns 1. 01) Is there a way for me to re ...

The OnClientSelectedIndexChanged event is not triggering when the dropdown selection is changed

I'm experiencing an issue with my OnClientSelectedIndexChanged javascript function not firing when the dropdown selected value is changed. Despite placing a breakpoint on the first line of the javascript function, it never gets reached. <t ...