ネストする代わりに promise をチェーンすることで、これを垂直構造に変換できます。
this.props.loadNutMatrixes({perPage:'all'})
.then(() => this.props.loadIngredients())
.then(() => this.props.getBadge())
.then(() => this.props.loadNutInfoItems({perPage:'all'}))
.then(() => this.props.getItemSize())
.then(() => this.props.getSingleMenuCategory(this.props.category_uid))
.then(() => this.props.loadAllStores(({per_page:'all'})))
.then(() => {
if (this.props.selectedMenuItem) {
initialize("addNewMenuItem", {
...this.props.selectedMenuItem
})
}
});
可能な改善は、引数を受け取るすべての promise 作成関数を引数なしの関数にラップし、props
代わりにそれらを渡すことです。
loadAllNutMatrixes() {
return this.loadNutMatrixes({ perPage: 'all' });
}
loadAllNutInfoItems() {
return this.loadNutInfoItems({ perPage: 'all' });
}
getSingleMenuCategoryFromId() {
return this.getSingleMenuCategory(this.category_uid);
}
loadEveryStory() {
return this.loadAllStores({ perPage: 'all' });
}
次に、最後のステップを独自のメソッドにリファクタリングできます。
onChainFinished() {
if (this.props.selectedMenuItem) {
initialize("addNewMenuItem", {
...this.props.selectedMenuItem
})
}
}
そして、この 2 つを分解して結合し、よりクリーンなチェーンを実現します。
const { props } = this;
props.loadAllNutMatrixes()
.then(props.loadIngredients)
.then(props.getBadge)
.then(props.loadAllNutInfoItems)
.then(props.getItemSize)
.then(props.getSingleMenuCategoryFromId)
.then(props.loadEveryStore)
.then(this.onChainFinished);
あなたのコメントに基づいて編集
promise.all のようなものを使用しますが、シリーズの方法で!
Promise をチェーンするためのネイティブ メソッドはありませんが、ユース ケースに適したヘルパー メソッドを構築してこれを行うことができます。一般的な例を次に示します。
// `cp` is a function that creates a promise and
// `args` is an array of arguments to pass into `cp`
chainPromises([
{ cp: this.props.loadNutMatrixes, args: [{perPage:'all'}] },
{ cp: this.props.loadIngredients },
{ cp: this.props.getBadge },
{ cp: this.props.loadNutInfoItems, args: [{perPage:'all'}] },
{ cp: this.props.getItemSize },
{ cp: this.props.getSingleMenuCategory, args: [this.props.category_uid] },
{ cp: this.props.loadAllStores, args: [{per_page:'all'}] }
]).then(() => {
if (this.props.selectedMenuItem) {
initialize("addNewMenuItem", {
...this.props.selectedMenuItem
})
}
});
function chainPromises(promises) {
return promises.reduce(
(chain, { cp, args = [] }) => {
// append the promise creating function to the chain
return chain.then(() => cp(...args));
}, Promise.resolve() // start the promise chain from a resolved promise
);
}
上記と同じアプローチを使用して引数付きのメソッドをリファクタリングすると、このコードもクリーンアップされます。
const { props } = this;
chainPropsPromises([
props.loadAllNutMatrixes,
props.loadIngredients,
props.getBadge,
props.loadAllNutInfoItems,
props.getItemSize,
props.getSingleMenuCategoryFromId,
props.loadEveryStory
])
.then(this.onChainFinished);
function chainPropsPromises(promises) {
return promises.reduce(
(chain, propsFunc) => (
chain.then(() => propsFunc());
), Promise.resolve()
);
}