Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

redux-promise-mutex

Package Overview
Dependencies
Maintainers
1
Versions
2
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

redux-promise-mutex

add mutex for redux-thunk

  • 1.0.1
  • latest
  • npm
  • Socket score

Version published
Maintainers
1
Created
Source

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

Keywords

FAQs

Package last updated on 22 Sep 2017

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc