いくつかの関数を抽出してPromiseチェーンをリファクタリングしたいと考えています。現在、私はPromiseチェーンでの関数の抽出
const getData = (uuid) => {
return new Promise((resolve) => {
fetch(
// go fetch stuff
)
.then((response) => {
if (!response.ok) {
return resolve(false);
}
return response;
})
.then(fetchres.json)
.then(response => {
// Do more stuff that requires resolves that I will also want to refactor
})
.catch(err => {
console.log(err);
resolve(false);
});
});
};
を持っているので、私は失敗した応答をresolve
部分を抽出したいです。しかし、成功したものに合格する。私はそれのようにそれを引っ張った。
const resolveUnsuccessfulResponses = (response) => {
if (!response.ok) {
return response.resolve(false);
}
return response;
}
const getData = (uuid) => {
return new Promise((resolve) => {
fetch(
// go fetch stuff
)
.then(resolveUnsuccessfulResponses)
.then(fetchres.json)
.then(response => {
// Do more stuff that requires resolves that I will also want to refactor
})
.catch(err => {
console.log(err);
resolve(false);
});
});
};
ここで私は間違いなくエラーresolve is not defined
を受け取りました。この約束を外部機能で解決するにはどうすればよいですか? 抽出した機能にresolve
を渡す必要がありますか?それはぎこちないように見えるでしょう。
.then(response => resolveUnsuccessfulResponses(response, resolve))
私は
.then(fetchres.json)
.then(parseResponseData)
.then(postDataSomewhere)
.then(doOtherThings)
.then(doEvenMoreCoolThings)
のようなものを持ってしまう可能性があり、それらのそれぞれにresponse
とresolve
を渡すために持っているあなたは、あなたの外部関数から新しい約束を返す必要があります
もしあなたが 'return resolve(f alse); 'あなたは間違っていると思う[連鎖を破る](http://stackoverflow.com/q/21576862/1048572)。そして、あなたは['Promise'コンストラクタの反パターンを避けるべきです(http://stackoverflow.com/q/23803743/1048572)! – Bergi
@Bergiプロミスのコンストラクタ反パターンのリンクをありがとう!また、はい、私はちょうどそれが今でも 'fetchres.json'に' false'を渡していることに気付きました。 –