javascript - 等待 redux 状态满足条件

标签 javascript asynchronous redux promise race-condition

我有以下函数,这意味着我可以等待特定条件进入我的 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/

相关文章:

java - jsp:如何从 session 中获取值?

javascript - Angularjs:使用 ng-option 时如何在 select 中包含空选项

asynchronous - 如何解决将 Future<dynamic> 实例作为参数传递的错误?

c# - .NET WebClient - 上传数据并获取流

javascript - 如何编写不带参数的类型化操作

reactjs - react native ,Redux : No Store Found

javascript - 如何在网页中存储值(字符串)

javascript - 在我的例子中如何使用 php 传递参数

asynchronous - hiredis 从异步上下文运行同步命令

javascript - 如何在 Chai 的单元测试中使用 localStorage