通过全局变量反应互斥体

时间:2018-11-01 00:56:18

标签: javascript reactjs concurrency mutex

我们正在使用ReactRedux
我们如何通过互斥锁来保护资源免于访问?

是否可以通过全局变量以及将其存储在哪里?
PS,由于状态更新延迟,我们不希望通过Redux做到这一点

提供更多上下文的小例子

export default function configureStore() {
  const store = createStore(rootReducer, persistedState, composedEnhancers);
  store.subscribe(
    // saveState saves state to localStorage
    // here we need mutex which will prevent state from saving to localStorage
    // and some way to toggle this mutex
    throttle(() => {
      saveState(store.getState());
    }, 2000),
  );
  return store;
}

2 个答案:

答案 0 :(得分:0)

我不确定这是否是正确的解决方法
请记住,这是有效的,因为store.subscribe监听了redux状态更改

export default function configureStore() {
  const store = createStore(rootReducer, persistedState, composedEnhancers);
    store.subscribe(
      throttle(() => {
        const currentState = store.getState();
        // if we allowing state to sync with localStorage
        if (currentState.isMutexVariable) {
          saveState(currentState);
        }
      }, 2000),
    );
  return store;
}

答案 1 :(得分:-1)

我可能无法完全理解您。您是否要让程序在继续执行下一行之前等待一行代码完成执行?这样,多个“事物”就不会同时访问同一资源。 您可以使用async / await函数来执行此操作。例如:

async function f() {

  let promise = new Promise((resolve, reject) => {
    setTimeout(() => resolve("done!"), 1000)
  });

  let result = await promise; // wait till the promise resolves (*)

  alert(result); // "done!"
}

f();