reactjs - 跨 redux sagas 同步令牌获取的最佳方法
问题描述
因此,我希望能够在所有命中特定 API 的 sagas 中使用一个通用函数来获取令牌。这就是我想出的
function* getValidAuthToken(params: TokenParams) {
// Refresh token 5 seconds before actual expiration. This gives some buffer time
// for inflight requests to succeed
const bufferTimeMS = 10000;
const token = yield select(tokenSelector);
if (token && Date.now() < token.tokenExpirationTimeStampMs - bufferTimeMS) {
return token.tokenValue;
}
const isUpdating = yield select(isCurrUpdatingToken);
// If another saga has already started the process to fetch a new token we just wait for that to finish
if (isUpdating) {
yield take(finishTokenUpdate);
const token = yield select(tokenSelector);
return token.tokenValue;
}
// Else we start the process to get a new lrs token
yield put(startTokenUpdate());
const result = yield sdk.getToken(params);
const { tokenValue, lifetimeSeconds } = result.token;
const tokenExpirationTimeStamp = Date.now() + lifetimeSeconds * 1000;
yield put(finishTokenUpdate({ tokenExpirationTimeStampMs: tokenExpirationTimeStamp, tokenValue }));
return tokenValue;
}
isUpdating
如果另一个消费者已经开始了这个过程,我包括了一个状态以避免获取令牌。在这种情况下,我只想等待令牌更新完成,然后获取结果。
但是我注意到在应用程序启动时......多个消费者同时调用我的服务。在这种情况下,isUpdating
标志没有时间改变,实际上它的比赛条件天气或不getToken
被多次调用。
解决方案
好吧,实际上我觉得自己很愚蠢......我发布这个的那一刻我发现了我的错误。
我的减速器是这样写的
import { finishTokenUpdate, startTokenUpdate } from './actions';
const isUpdatingTokenHanlder = handleActions(
{
startTokenupdate: (state, action) => true,
finishTokenUpdate: (state, action) => false,
},
false,
);
这没有正确定义我的操作键。相反,它应该是
const isUpdatingTokenHanlder = handleActions(
{
[`${startTokenUpdate}`]: (state, action) => true,
....
);
推荐阅读
- flyway - 如何在没有 DDL 脚本的情况下将 Flyway 添加到现有数据库?
- android - Firebase crashlytics 错误:无法加载类“org.gradle.api.tasks.TaskProvider”
- c - 为什么我们不能使用 const int 来初始化 char 数组的大小?
- javascript - dc.js:TypeError:将 HtmlLegend 添加到条形图时无法读取未定义的属性“0”
- asp.net-core - ASP.NET Core Web API - AmbiguousMatchException:请求匹配多个端点
- c# - 我的 ASP.NET Core MVVM Blazor 应用程序的依赖注入无法正常工作
- python - 查找反向字符串是否在字符串列表中匹配
- javascript - 将对象数组转换为数组并通过 Axios 作为 GET API 的参数发送
- python - 如何在 Python 中使用正则表达式查找 javascript 文件中的所有路径?
- node.js - 安装后运行sass时出现问题