Axios / Vue - 防止axios.all()继续执行

问题描述 投票:16回答:3

在我的应用程序中,我会调用fetchData函数来验证用户身份。如果用户令牌变为无效,应用程序将运行axios.all()并且我的拦截器将返回许多错误。

如何防止axios.all()在第一次出错后继续运行?并只向用户显示一个通知?

interceptors.js

export default (http, store, router) => {
    http.interceptors.response.use(response => response, (error) => {
        const {response} = error;

        let message = 'Ops. Algo de errado aconteceu...';

        if([401].indexOf(response.status) > -1){
            localforage.removeItem('token');

            router.push({
                name: 'login'
            });

            Vue.notify({
                group: 'panel',
                type: 'error',
                duration: 5000,
                text: response.data.message ? response.data.message : message
            });
        }

        return Promise.reject(error);
    })
}

auth.js

const actions = {
    fetchData({commit, dispatch}) {
        function getChannels() {
            return http.get('channels')
        }

        function getContacts() {
            return http.get('conversations')
        }

        function getEventActions() {
            return http.get('events/actions')
        }

        // 20 more functions calls

        axios.all([
            getChannels(),
            getContacts(),
            getEventActions()
        ]).then(axios.spread(function (channels, contacts, eventActions) {
            dispatch('channels/setChannels', channels.data, {root: true})
            dispatch('contacts/setContacts', contacts.data, {root: true})
            dispatch('events/setActions', eventActions.data, {root: true})
        }))
    }
}
javascript vue.js axios vue-cli
3个回答
6
投票

编辑:@tony19's answer更好,因为它允许取消在第一次错误后仍然挂起的请求,并且不需要任何额外的库。


一种解决方案是为您同时使用的所有请求分配一个唯一标识符(我将在此示例中使用uuid/v4包,随意使用其他内容):

import uuid from 'uuid/v4'

const actions = {
    fetchData({commit, dispatch}) {
        const config = {
            _uuid: uuid()
        }

        function getChannels() {
            return http.get('channels', config)
        }

        function getContacts() {
            return http.get('conversations', config)
        }

        function getEventActions() {
            return http.get('events/actions', config)
        }

        // 20 more functions calls

        axios.all([
            getChannels(),
            getContacts(),
            getEventActions()
        ]).then(axios.spread(function (channels, contacts, eventActions) {
            dispatch('channels/setChannels', channels.data, {root: true})
            dispatch('contacts/setContacts', contacts.data, {root: true})
            dispatch('events/setActions', eventActions.data, {root: true})
        }))
    }
}

然后,在您的拦截器中,您可以选择使用此唯一标识符一次处理错误:

export default (http, store, router) => {
    // Here, you create a variable that memorize all the uuid that have
    // already been handled
    const handledErrors = {}
    http.interceptors.response.use(response => response, (error) => {
        // Here, you check if you have already handled the error
        if (error.config._uuid && handledErrors[error.config._uuid]) {
            return Promise.reject(error)
        }

        // If the request contains a uuid, you tell 
        // the handledErrors variable that you handled
        // this particular uuid
        if (error.config._uuid) {
            handledErrors[error.config._uuid] = true
        }

        // And then you continue on your normal behavior

        const {response} = error;

        let message = 'Ops. Algo de errado aconteceu...';

        if([401].indexOf(response.status) > -1){
            localforage.removeItem('token');

            router.push({
                name: 'login'
            });

            Vue.notify({
                group: 'panel',
                type: 'error',
                duration: 5000,
                text: response.data.message ? response.data.message : message
            });
        }

        return Promise.reject(error);
    })
}

另外请注意,您可以将fetchData函数简化为:

const actions = {
    fetchData({commit, dispatch}) {
        const config = {
            _uuid: uuid()
        }

        const calls = [
            'channels',
            'conversations',
            'events/actions'
        ].map(call => http.get(call, config))

        // 20 more functions calls

        axios.all(calls).then(axios.spread(function (channels, contacts, eventActions) {
            dispatch('channels/setChannels', channels.data, {root: true})
            dispatch('contacts/setContacts', contacts.data, {root: true})
            dispatch('events/setActions', eventActions.data, {root: true})
        }))
    }
}

2
投票

作为Axios取消的替代方案,您可以使用更简单的Bluebird Promise Cancellation

与旧取消相比,新取消的优点是:

  • .cancel()是同步的。
  • 取消工作不需要设置代码
  • 与其他蓝鸟功能组合,如Promise.all

这是一个演示。我在axios.get(...).then(...)中添加了一些日志记录,以跟踪每个调用是否完成。

注释掉行promises.forEach(p => p.cancel())以验证没有取消,非错误调用将运行完成。

//for demo, check if fetch completes 
const logCompleted = (res) => console.log(`Promise completed, '${res.config.url}'`) 

function getChannels() {
  return axios.get("https://reqres.in/api/users?page=1&delay=5").then(logCompleted)
}
function getContacts() {
  return axios.get("https://reqres.in/api/users?page=2").then(logCompleted)
}
function getEventActions() {
  return axios.get("https://httpbin.org/status/401").then(logCompleted)
}

Promise.config({ cancellation: true }); // Bluebird config
window.Promise = Promise; // axios promises are now Bluebird flavor

const promises = [getChannels(), getContacts(), getEventActions()];
Promise.all(promises)
  .then(([channels, contacts, eventActions]) => {
    console.log('Promise.all.then', { channels, contacts, eventActions });
  })
  .catch(err => {
    console.log(`Promise.all.catch, '${err.message}'`)
    promises.forEach(p => p.cancel());
  })
  .finally(() => console.log('Promise.all.finally'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/bluebird/latest/bluebird.core.min.js"></script>

为什么会这样

Promise.all()而不是axios.all()

看看这个老axios问题Remove axios.all and axios.spread #1042可以看到

Axios在引擎盖下使用Promise.all ......

还有这个

axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // Both requests are now complete
}));

可以用这个代替

Promise.all([getUserAccount(), getUserPermissions()])
  .then(function ([acct, perms]) {
    // Both requests are now complete
});

所以我们可以直接切换到与Promise一起使用,并且仍然具有相同的功能。


承诺失败很快

MDN我们看到

如果任何元素被拒绝,Promise.all将被拒绝。例如,如果传入四个在超时后解析的promise和一个立即拒绝的promise,则Promise.all将立即拒绝。

所以在这种模式中

Promise.all(...)
.then(...)
.catch(...);

当第一个承诺失败时,.catch()将触发(与then()相反,等待所有承诺完成)。


组成Promise.all.cancel()

模式非常简单,只需取消.catch()中的所有承诺(在第一次错误时调用)。

有关详细信息,请参阅此问题Stop other promises when Promise.all() rejects


在Vue商店代替Bluebird

这是Vuex中的基本实现。

yarn add bluebird
import Vue from "vue";
import Vuex from "vuex";
import axios from "axios";
import Promise from 'bluebird';
Vue.use(Vuex);

Promise.config({ cancellation: true }); // Bluebird config
window.Promise = Promise; // axios promises are now Bluebird flavor

export default new Vuex.Store({
  actions: {
    fetchData({ dispatch }) {
      function getChannels() {
        return axios.get("https://reqres.in/api/users?page=1&delay=5");
      }
      function getContacts() {
        return axios.get("https://reqres.in/api/users?page=2");
      }
      function getEventActions() {  // 401 - auth error
        return axios.get("https://httpbin.org/status/401");
      }

      const promises = [getChannels(), getContacts(), getEventActions()];
      Promise.all(promises)
        .then(([channels, contacts, eventActions]) => {
          dispatch("channels/setChannels", channels.data, { root: true });
          dispatch("contacts/setContacts", contacts.data, { root: true });
          dispatch("events/setActions", eventActions.data, { root: true });
        })
        .catch(err => {
          promises.forEach(p => p.cancel());
        })
    }
  }
});

1
投票

upvoted answer提出了一个解决方案,需要等待所有响应完成,对uuid的依赖,以及拦截器的一些复杂性。我的解决方案避免了所有这些并解决了终止Promise.all()执行的目标。

Axios支持request cancelation,因此您可以使用错误处理程序包装GET请求,该处理程序立即取消其他待处理请求:

fetchData({ dispatch }) {
  const source = axios.CancelToken.source();

  // wrapper for GET requests
  function get(url) {
    return axios.get(url, {
        cancelToken: source.token // watch token for cancellation
      }).catch(error => {
        if (axios.isCancel(error)) {
          console.warn(`canceled ${url}, error: ${error.message}`)
        } else {
          source.cancel(error.message) // mark cancellation for all token watchers
        }
      })
  }

  function getChannels() {
    return get('https://reqres.in/api/users?page=1&delay=30'); // delayed 30 secs
  }
  function getContacts() {
    return get('https://reqres.in/api/users?page=2'); // no delay
  }
  function getEventActions() {
    return get('https://httpbin.org/status/401'); // 401 - auth error
  }

  ...
}

在您的拦截器中,您还会忽略请求取消中的错误:

export default (http, store, router) => {
  http.interceptors.response.use(
    response => response,
    error => {
      if (http.isCancel(error)) {
        return Promise.reject(error)
      }

      ...

      // show notification here
    }
}

demo

© www.soinside.com 2019 - 2024. All rights reserved.