【发布时间】:2016-07-01 21:41:44
【问题描述】:
稍后我会解释我为什么要这样做。 这是问题所在。我有一个返回如下承诺的函数:
const testFunc = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (Math.random() > 0.5) {
resolve('succeeded');
} else {
reject('failed');
}
}, 1000);
});
};
正如所料,我可以这样调用它就好了:
testFunc()
.then((result) => console.log(result)) // 'succeeded'
.catch((error) => console.log(error)); // 'failed'
或者把它赋值给一个变量,这样调用它
const testFuncVar = testFunc;
testFuncVar()
.then((result) => console.log(result)) // 'succeeded'
.catch((error) => console.log(error)); // 'failed'
这些都是意料之中的。但是,一旦我将函数置于 redux 状态,然后从那里调用它,它就不再起作用了。这是我所做的(非常简化)。
const initialState = {testFunc: testFunc};
// redux reducer, action creator, etc.
...
...
// somewhere later. Here I'm using redux-thunk to access redux state
function testFunInState() {
return (dispatch, getState) => {
const {testFunc} = getState();
// this is not working
testFunc()
.then((result) => console.log(result))
.catch((error) => console.log(error));
};
}
我得到的错误是_promise2 is not defined。注意变量名_promise2应该来自babel transpiler。如果我console.log(state.testFunc) 或console.log(testFunc),我得到:
testFunc() {
return new _promise2.default(function (resolve, reject) {
if (Math.random() > 0.5) {
resolve('succeeded');
} else {
reject('failed');
}
});
}
所以Promise 对象在函数处于 redux 状态时会以某种方式丢失?
但我确实找到了解决方法。如果我将功能更改为
const testFunc = (resolve, reject) => {
setTimeout(() => {
if (Math.random() > 0.5) {
resolve('succeeded');
} else {
reject('failed');
}
}, 1000);
};
并用resolve和reject作为参数传入调用它,那么我很好。
// this works
new Promise((resolve, reject) => state.testFunc(resolve, reject))
.then((result) => console.log(result))
.catch((error) => console.log(error));
我想知道为什么一个返回 promise 的函数在放入 redux store 后就不起作用,而一个没有返回 promise 的函数起作用?
现在谈谈我为什么要这样做。我想要实现的是拥有一个定期调度一些异步操作的作业队列,并根据结果(解决或拒绝)执行其他操作(如重试或发送通知)。我想动态地在队列中添加/删除作业,因此很难有一个可以处理所有可能操作的减速器。感觉这是一种合理的处理方式。我愿意接受建议。
【问题讨论】:
-
这很令人困惑,尤其是错误,因为在发布的代码中似乎没有
_promise2...任何东西 ..? -
我高度怀疑您遇到的错误未在此 sn-p 中显示。函数返回什么并不重要,您只是在存储中存储对它的引用。
-
@adeneo
_promise2应该来自 bable 转译器。我已编辑问题以使其更清楚。 -
在
statestate上贴上你标记promise func的reducer代码 -
@lux,我正在使用 redux-thunk 访问状态中的
testFunc。我对原始问题进行了额外的编辑。 @AlexG,我有同样的理解,返回的内容并不重要,因为我只是存储对函数的引用。但不知何故,每当我在函数中有new Promise时,它就会停止工作。
标签: javascript reactjs redux es6-promise react-redux