我有以下函数,这意味着我可以等待特定条件进入我的 redux 状态。
async function when(store, condition) {
if (condition(store.getState())) {
return;
} else {
return new Promise(resolve => {
const unsubscribe = store.subscribe(() => {
if (condition(store.getState())) {
unsubscribe();
resolve();
}
});
});
}
}
但是,我正在努力弄清楚这是否没有竞争条件。特别是,如果我有一个像...这样的函数:
async function foo(store) {
await when(store, thereAreExactlyThreeTodoItems);
doSomethingThatRequiresExactlyThreeTodoItems();
}
...我能否保证在调用 doSomethingThatRequiresExactlyThreeTodoItems()
时,thereAreExactlyThreeTodoItems()
表示的条件为 true
?还是说这需要进一步的步骤来保证?即:
async function foo(store) {
do {
await when(store, thereAreExactlyThreeTodoItems);
} while (!thereAreExactlyThreeTodoItems(store.getState());
doSomethingThatRequiresExactlyThreeTodoItems();
}
我担心的是:在调用 resolve()
之后、但在控制权返回到 foo()
之前,是否可以调度一个使条件无效的操作?不幸的是,我没有足够好的 javascript 事件循环心智模型来确定。
非常感谢任何帮助。
最佳答案
你正在尝试做的事情看起来不错,唯一看起来奇怪的是你没有缓存 promise 创建......
我认为您必须创建一个映射并缓存创建的 promise ,这样您就不会为相同的功能创建新的 promise 。
在这种情况下,我看不出有什么办法可以解决竞争条件问题。
类似的事情:
const cache = {}
function when(store, condition, id) {
if (condition(store.getState())) {
return;
} else if(!cache[id]) {
cache[id] = true;
return new Promise(resolve => {
const unsubscribe = store.subscribe(() => {
if (condition(store.getState())) {
unsubscribe();
resolve();
delete cache[id]
}
});
});
}
}
}
关于javascript - 等待 redux 状态满足条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57435228/