重新运行错误并传递结果

时间:2017-12-30 18:37:24

标签: javascript promise vuejs2

我把我的api电话分成了三层。 componentrepositoryapihelper。我希望refresh_tokens的逻辑位于apihelper.js。当我这样做时,似乎apihelper在获得401响应状态后再次运行,但它从未将数据传递回component。我知道我可以把逻辑重新运行在组件中,但是当我添加更多调用时,它似乎最终会成为很多重复的代码。我觉得这可能是由于我对javascript承诺的浅薄理解引起的,但我是一个javascript初学者。

组件

<script>
import breweryrepository from '@/repository/breweryrepository.js'
export default {
    mounted() {
        this._getTotalBreweries();
    },
    methods: {
        _getTotalBreweries() {
            breweryrepository.getTotalBreweries()            
                .then((response) => {
                    if(response.data)
                    {
                        this.totalNumberOfBreweries = response.data.totalBreweries;
                    }
                })
        }
    },
    data () {
        return {
            totalNumberOfBreweries: ''
        }
    }
}
</script>

存储库

import apihelper from '@/helpers/ApiHelper.js';

export default {  

  getTotalBreweries() {
    return new Promise(function(resolve, reject) {
      resolve(apihelper.apiCall('/brewery/totalnumber'));
    });      
  }
} 

Apihelper

import axios from 'axios';
var querystring = require('querystring');
import { store } from '../store/store.js';
import auth from '@/auth/auth.js'

export default {       
  apiCall(url) {
    return axios.get(store.state.baseUrl + url, { 'headers': auth.getAuthHeader() })
      .catch((error) => {                    
        if(error.response.status == 401)
        {
          console.log("401 error, running refresh and apicall again");
          auth.refreshToken();
          this.apiCall(url);                          
        }
    })
  }
}  

1 个答案:

答案 0 :(得分:0)

Aaaa和我没有回电话。

return this.apiCall(url);

立即投放