通过全局变量反应互斥量
React mutex via global variable
我们正在使用 React
和 Redux
我们如何借助互斥锁来保护资源不被访问?
是否可以通过全局变量来执行此操作以及将它们存储在何处?
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;
}
我可能没有完全理解你。您是否试图让程序等待一行代码执行完后再继续下一行?这样,多个 "things" 就不会同时访问同一个资源。
您可以使用 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();
我不确定这是否是正确的解决方案
请记住,这是有效的,因为 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;
}
我们正在使用 React
和 Redux
我们如何借助互斥锁来保护资源不被访问?
是否可以通过全局变量来执行此操作以及将它们存储在何处?
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;
}
我可能没有完全理解你。您是否试图让程序等待一行代码执行完后再继续下一行?这样,多个 "things" 就不会同时访问同一个资源。 您可以使用 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();
我不确定这是否是正确的解决方案
请记住,这是有效的,因为 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;
}