なぜこれを後で行うか説明します。 ここに問題があります。予想通り、私はちょうど罰金このようにそれを呼び出すことができます還元状態で約束を返す関数を置きます
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のものでなければなりません。 I 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');
}
});
}
機能がReduxの状態に置かれるたびだから、何とかPromise
オブジェクトが失われてしまいましたか?
しかし、私は回避策を見つけました。私は
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));
それは約束の作品を返さずにReduxの店が、1に入れていたら、約束を返す関数が動作しない理由を私は思ったんだけど?
私はなぜこのようにしたいのですか?私が達成しようとしているのは、定期的にいくつかの非同期アクションをディスパッチし、結果に応じて(解決または拒否)、何か他のことをやり直す(通知を送信するなど)ジョブキューを持つことです。私は動的にキューに/からジョブを追加/削除したいので、可能なすべてのアクションを処理できるリデューサーを持つことは難しいです。これはそれがそれに近づく合理的な方法だと感じています。私は提案に開放されています。
経由Reduxの状態に
testFunc
を追加するためのコードです。..投稿されたコードに? – adeneo私はあなたが遭遇したバグがこのスニペットに表示されていないと非常に疑います。関数が返すものは問題ではなく、ストアへの参照をストアするだけです。 – AlexG
@adeneo '_promise2'はbable transpilerのものでなければなりません。私はそれをより明確にするために質問を編集しました。 – realbug