Javascript承诺和错误处理 - trycatch

问题描述 投票:0回答:1

需要帮助,因为我不明白的东西... ...

我明白了

// AuthService.js
login(user) {
    return Api.post('/login', user);
},


// store/user.js
async login(context, user) {
    try {
        let response = await AuthService.login(user);
        context.commit('SET_TOKEN', response.data.api_token);

        response = await AuthService.me();
        context.commit('SET_USER', response.data.user)
    }catch (e) {
        console.log(e);
    }
},

// Login.vue
async onSubmit() {
    await this.$store.dispatch('user/login', this.user);
    this.$router.push({name: 'Home'});
}

我知道axios返回了一个承诺 所以我可以在storeuser中asyncawait等待响应。但我真的卡住了,我想把错误发送到Login组件,以停止router.push和重定向。

解决方法。

// AuthService.js
login(user) {
    return Api.post('/login', user);
},


// store/user.js
async login(context, user) {
    let response = await AuthService.login(user);
    context.commit('SET_TOKEN', response.data.api_token);

    response = await AuthService.me();
    context.commit('SET_USER', response.data.user)
},

// Login.vue
async onSubmit() {
    try {
        await this.$store.dispatch('user/login', this.user);
        this.$router.push({name: 'Home'});
    } catch (e) {
        console.log(e);
    }
}
javascript vue.js axios try-catch es6-promise
1个回答
1
投票

你的程序会在登录后继续,要么你得到一个错误或没有。你应该停止,并处理错误。

由于这种情况,这个错误取决于UI,所以你必须在你的组件上处理这个ajax请求来处理这个错误。

我认为你需要改变一下你的代码架构来解决这个问题(你不需要触发登录动作)。

// Login.vue
async onSubmit() {
    try {
        let response = await AuthService.login(user);
        context.commit('SET_TOKEN', response.data.api_token);

        response = await AuthService.me();
        context.commit('SET_USER', response.data.user);
        
        this.$router.push({name: 'Home'});
    } catch (e) {
        // handle what happens when you got errors
        // or throw e;
    }
}

0
投票

理想情况下,你应该在重定向之前检查token是否设置成功。下面我将token设置为 null 如果登录失败,你的AuthService调用。在您的提交事件中,我在重定向到正确的路径之前,会检查store是否有token值。

async login(context, user) {
  try {
    let response = await AuthService.login(user);
    context.commit('SET_TOKEN', response.data.api_token);

    response = await AuthService.me();
    context.commit('SET_USER', response.data.user)
  }catch (e) {
    console.log(e);
    // --> set the token as null, since it failed the login
    context.commit('SET_TOKEN', null);

  }
},

// Login.vue
async onSubmit() {
  await this.$store.dispatch('user/login', this.user);
  // --> Here check if the SET_TOKEN is present before redirecting to home
  if(this.$store.state.token == null) {
    this.$router.push({name: 'Login'});

  } else {
    this.$router.push({name: 'Home'});
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.