我正在使用 Electron、React 和 Redux 开发一个应用程序。在程序启动时,我在渲染进程和主进程之间进行一些异步 ipc 调用,并将结果保存在存储中。
// in the main app component
componentWillMount() {
const { store } = this.context;
store.dispatch(fetchOptions());
store.dispatch(fetchRequirements());
store.dispatch(fetchStats());
/* miracle function */
},
// actions.js
export function fetchOptions() {
return dispatch => {
dispatch(requestOptions());
ipcRenderer.on('sendOptions', function(event, arg) {
dispatch(receiveOptions(arg));
});
ipcRenderer.send('requestOptions', '');
};
}
// others accordingly
receiveOptions(arg)
、receiveRequirements(arg)
和 receiveStats(arg)
是操作创建者,最后,reducer 会将响应保存在商店。
紧接着 store.dispatch(fetchStats())
,我想调度另一个操作来根据加载到存储中的值进行一些计算。但是,此操作通常会在 ipc 的响应到达之前调度。
我找到了this discussion遇到类似的问题,但他们使用 fetch
而不是 ipc 消息进行 api 调用,我不知道如何将他们的想法应用于我的问题。
所以这是我的问题:如何让程序在继续之前等待所有 channel 的响应?
编辑:当我在 ipc 调用后为调度设置长度为 0 的时间时,它至少可以立即响应,但当然当响应需要更长的时间时它没有帮助。
store.dispatch(fetchOptions());
store.dispatch(fetchRequirements());
store.dispatch(fetchStats());
setTimeout(function() {
store.dispatch(calculateThis());
store.dispatch(calculateThat());
}, 0);
最佳答案
使用 Promises 的示例
假设
我不熟悉您的 icpRenderer
的工作原理,也不熟悉调度完成时的 exaclty。我将假设在调用 dispatch(receiveOptions(arg))
返回后完成调度
ipcRenderer.on('sendOptions', function(event, arg) {
dispatch(receiveOptions(arg));
});
如果 dispatch()
是异步的,这将不起作用(除非您等到 dispatch()
完成后才解决 promise )。
如果我的假设是正确的
您应该能够返回收到这样的“ promise ”(并解决它)
// actions.js
export function fetchOptions(promise) {
return dispatch => {
dispatch(requestOptions());
ipcRenderer.on('sendOptions', function(event, arg) {
dispatch(receiveOptions(arg));
if (promise) promise.resolve(); // Resolve the promise
});
ipcRenderer.send('requestOptions', '');
}
}
// return Promises others accordingly
(请注意,您可以在不传递“promise”的情况下调用 fetchOptions,因为如果存在promise,我们只会调用promise.resolve()。因此,这不会使您现有的代码变得复杂。)
为了等待 promise 解决,你可以这样做
// in the main app component
componentWillMount() {
const { store } = this.context;
const promises = [
new Promise((resolve, reject) =>
store.dispatch(fetchOptions({resolve, reject}))),
new Promise((resolve, reject) =>
store.dispatch(fetchRequirements({resolve, reject}))),
new Promise((resolve, reject) =>
store.dispatch(fetchStats({resolve, reject})))
];
Promise.all(promises).then(() =>
// Dispatch another action after the first three dispatches are completed.
);
},
代码并没有变得非常干净,但希望它至少能工作。
关于javascript - 在 Electron/Redux 中继续之前等待多个 IPC 调用完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35985917/