vue router next()函数在router.beforeEach中的Promise中不起作用

Gos*_*ull 5 vue.js vue-router

我有以下代码:

router.beforeEach((to, from, next) => {
  if (to.name !== from.name) {
    store
      .dispatch("fetchCurrentUser")
      .then(() => {
        console.log('then');
        // do something
        next();
      })
      .catch(() => {
        console.log('catch');
        router.push("/login");
        next();
    });
  } else {
    next();
  }
  // next();
});
Run Code Online (Sandbox Code Playgroud)

我正在尝试获取当前用户,如果成功,则使用此数据进行操作,如果请求未成功,则将用户重定向到登录页面。但是next()调用不起作用,我在控制台中得到了“ then”或“ catch”,但是没有发生重定向,并且开始了无限循环。但是,如果我从条件(带注释的行)中获取next(),则重定向工作正常。

Rad*_*iță 0

promise函数结束后解析。

next这意味着无论承诺结果如何,注释都会发生。然后这个 Promise 就解决了,你再调用另一个 Promise next

最重要的是,您不需要注释next,而应该只覆盖承诺解析。