1.0.1 • Published 7 years ago
redux-promise-mutex v1.0.1
redux-promise-mutex
配合redux-thunk使用,可以自动对一些异步的action加锁。
使用场景
- 触发了一个异步的action,处理时间比较长,如果这个时候用户继续操作会不断触发新的action。如果不希望重复请求通常需要我们手动加锁处理,而使用了redux-promise-mutex后只需要按照一定规则书写action即可自动加锁。
如何使用
/* Store */
import { createStore, applyMiddleware } from 'redux';
import thunkMiddleware from 'redux-thunk';
import promiseMutex from 'redux-promise-mutex';
// promiseMutex 位置必须在 redux-thunk 之前
const middlewares = [promiseMutex, thunkMiddleware];
const store = createStore(
reducers,
applyMiddleware(...middlewares)
);
/* Actions */
function doAsync(startTime) {
// actions 必须返回函数(与redux-thunk相同),且该函数不能为匿名函数
return function doAsync(dispatch) {
//函数必须返回一个Promise/类Promise对象
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Done!');
}, 2000);
}).then((res) => {
const now = Date.now();
console.log('get: ' + res + ' cost: ' + (now - startTime) + 'ms');
});
}
}
/* Pages */
dispatch(doAsync(Date.now()));
具体要求
0、中间件顺序必须在redux-thunk之前 1、action 返回一个函数。(这个也是 redux-thunk 异步操作的要求) 2、action 返回的函数必须是 非匿名函数 ,或者函数带有 uuid 属性 3、函数返回值为 Promise / 类Promise 对象(可以进行then操作)
为何要使用?
可以过滤掉短时间内重复的action。
/* without redux-promise-mutex */
for(let i = 0; i < 10; i++) {
dispatch(doAsync(Date.now()));
}
// => 2秒后有10个console
/* with redux-promise-mutex */
for(let i = 0; i < 10; i++) {
dispatch(doAsync(Date.now()));
}
// => 2秒后只有1个console