【问题标题】:How to return boolean with axios如何使用 axios 返回布尔值
【发布时间】:2018-01-12 04:59:46
【问题描述】:

在 VueJS 中,我试图用 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;
    }));
  }

console.log 刚刚返回

承诺{[[PromiseStatus]]:“待定”,[[PromiseValue]]:未定义}

但我想要的是真或假作为回报。

【问题讨论】:

标签: javascript vue.js boolean vuejs2 axios


【解决方案1】:

问题不在于 VueJS 也不在于 Axios……我认为你误解了 Promises

你的函数是异步的,使用 Promises 解决问题,还有 axios。

要让 allContactsSaved() 返回 true/false 以供以后使用,您有 3 个选项:

1.承诺

返回一个承诺,并在调用 allContactsSaved 时使用 .then,如下所示:

 // 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。回调

我认为第一个选项比这个更好。这有点老派的方式。

 // 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.异步/等待

这是 ES6/7 的新功能,取决于 JS 引擎的版本,你需要一个转译器

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

【讨论】:

    【解决方案2】:

    您可以使用every 来确保每个联系人都已保存

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

    但这仍然会返回一个承诺 您可以链接另一个承诺:

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

    }

    【讨论】:

    • 我在 console.log 中得到了正确的输出。但是,如果我在其他地方调用该函数来检查它是否返回 true 或 false,因为它是异步的,所以我没有及时得到返回。我该如何等待响应?
    • 返回allContactsSaved中的promise,使用promise时调用.then
    猜你喜欢
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-07
    相关资源
    最近更新 更多