Mango D
Mango D

Reputation: 473

How to return boolean with axios

In VueJS I am trying to return a boolean with axios

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 is just returning

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

But I want either true or false in return.

Upvotes: 4

Views: 11055

Answers (2)

Lucas Katayama
Lucas Katayama

Reputation: 4580

The problem is not with VueJS neither Axios... I think you misunderstand Promises

Your function is asynchronous and use Promises to solve the problem, as well as axios.

To have allContactsSaved() returning with true/false to be used later, you have 3 options:

1. Promises

Return a promise, and use .then when allContactsSaved is called, like this:

 // 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;
  }

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

2. Callbacks

I think the first option is better than this one. This is kinda old school way.

 // 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 function callback:
 allContactsSaved(function(isSaved) {
     console.log(isSaved);
 });

3. Async/await

This is new for ES6/7 and depends on the version of JS engine, you will need a transpiler

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

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

Upvotes: 5

Posva
Posva

Reputation: 1102

You can use every to make sure every contact is saved

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

But this will still return a promise you can chain another promise:

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

}

Upvotes: 1

Related Questions