简体   繁体   English

承诺不等待解决或拒绝 - javascript - ReactJs

[英]Promises does not wait resolve or reject - javascript - ReactJs

I use to token authentication for my react spa app.我用来为我的 react spa 应用程序进行令牌身份验证。 Before I CRUD process, I check refresh token expiration time.在进行 CRUD 处理之前,我会检查刷新令牌过期时间。 If refresh token is valid, No problem but If is'nt valid it, I send old refresh token and receive new refresh and access token from server before crud.如果刷新令牌有效,没问题,但如果它无效,我发送旧的刷新令牌并在 crud 之前从服务器接收新的刷新和访问令牌。 No problem until this point.到此为止没问题。

Problem is the refresh mechanism completes without waiting for the response from the server.问题是刷新机制完成而不等待服务器的响应。

currentUser store the token value. currentUser 存储令牌值。 I check null control for token and then if expiration time not valid, I send old refresh token.我检查 null 控件的令牌,然后如果到期时间无效,我发送旧的刷新令牌。

At this point the function returns without waiting for the response of the authenticationService.createAccessTokenByRefreshToken function.此时 function 无需等待authenticationService.createAccessTokenByRefreshToken function 的响应即可返回。 Function must be wait this function because If access token is not valid, I need new one. Function 必须等待这个 function 因为如果访问令牌无效,我需要新的。

Why does the function end without waiting?为什么function不等待就结束了?

export function authHeader() {
    var authorization = {
        Authorization: ''
    };

    var currentUser = authenticationService.currentUserValue;

    if (currentUser && currentUser.token) {
        const refreshToken = currentUser.refreshToken;
        const expiration = currentUser.expiration;
        var moment = require('moment');
        var now = moment();

        if (moment(now).isAfter(expiration)) {
            authenticationService.createAccessTokenByRefreshToken(refreshToken).then((res) => {
                authorization.Authorization = `Bearer ${res.data.token}`;
                return Promise.resolve(authorization);
            });
        }
        else {
            authorization.Authorization = `Bearer ${currentUser.token}`;
            return Promise.resolve(authorization);
        }

        //return { Authorization: `Bearer ${currentUser.token}` };
    } else {
        return Promise.reject(authorization);
    }
}
if (moment(now).isAfter(expiration)) {
  authenticationService.createAccessTokenByRefreshToken(refreshToken).then((res) => {
    authorization.Authorization = `Bearer ${res.data.token}`;
    return Promise.resolve(authorization);
  });
}

This block of code needs a return statement.此代码块需要一个 return 语句。 At the moment it's implicitly returning undefined.目前它隐含地返回未定义。 Also, a small thing: if you're in a .then you don't need to do Promise.resolve(authorization), you can just return authorization .另外,一件小事:如果你在一个.then你不需要做Promise.resolve(authorization),你可以只返回authorization The .then creates a new promise for you. .then为您创建一个新的 promise。

if (moment(now).isAfter(expiration)) {
  return authenticationService.createAccessTokenByRefreshToken(refreshToken)
    .then((res) => {
      authorization.Authorization = `Bearer ${res.data.token}`;
      return authorization;
    });
}

please start using async await .请开始使用async await It makes your life easier and much readable code with fewer bugs.它使您的生活更轻松,代码更易读,错误更少。 Let me know if the following works fine for you:)让我知道以下内容是否适合您:)

const moment = require("moment");

const authHeader = async () => {
  try {
    const authorization = {
      Authorization: ""
    };

    const currentUser = authenticationService.currentUserValue;

    if (currentUser && currentUser.token) {
      const refreshToken = currentUser.refreshToken;
      const expiration = currentUser.expiration;
      const now = moment();

      if (moment(now).isAfter(expiration)) {
        const authResponse = await authenticationService.createAccessTokenByRefreshToken(
          refreshToken
        );
        authorization.Authorization = `Bearer ${authResponse.data.token}`;
      } else {
        authorization.Authorization = `Bearer ${currentUser.token}`;
      }
    }

    return authorization;
  } catch (err) {
    return err;
  }
};

export default authHeader;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM