Node.jsでは、ファイルを読み込んでその内容をすべて非同期で検証する必要があります。私はのNode.js 6.6、ブルーバード3.4.6複数のキャッチで約束を止める
例コードを使用してM:
// pseudo function to read file contents - resolves when 'flag' is true, rejects when 'flag' is false.
function readFile(flag) {
return new Promise(function (resolve, reject) {
console.log('Reading file...');
if (flag) {
resolve('File contents');
} else {
reject('readFile error');
}
});
}
// pseudo function to validate file contents - resolves when 'flag' is true, rejects when 'flag' is false.
function validate(fileContents, flag) {
return new Promise(function (resolve, reject) {
console.log('Validating file: ', fileContents);
if (flag) {
resolve('Validate passed');
} else {
reject('validation failed');
}
});
}
readFile(false)
.then(function (fileContents) {
console.log('Successfully read the file:', fileContents);
return fileContents;
})
.catch(function (fileReadErr) {
console.log('Failed to read the file:', fileReadErr);
throw fileReadErr; // or, return Promise.reject(err);
})
.then(function (fileContents) {
return validate(fileContents, false);
})
.then(function (result) {
console.log('Successfully validated the file:', result);
})
.catch(function (err) {
console.log('Failed to validate the file:', err);
})
;
<script src="https://cdn.jsdelivr.net/bluebird/3.4.6/bluebird.min.js"></script>
は、上記のコードが印刷され
Reading file...
Failed to read the file: readFile error
Failed to validate the file: readFile error
上記に約束チェーンはおおよそ以下の同期コードに変換されます:
try {
let fileContents;
try {
fileContents = readFile(false);
console.log('Successfully read the file:', fileContents);
} catch (e) {
console.log('Failed to read the file:', e);
throw e;
}
let validationResult = validate(fileContents, false);
console.log('Successfully validated the file:', validationResult);
} catch (err) {
console.log('Failed to validate the file:', err);
}
そして、まだ第二catch
方法を呼び出します最初catch
の方法で投げるか、拒否します。
私の質問:ファイルの読み込みが失敗したらチェーンを破る方法はありますか?私の目的は、express.jsルートからさまざまなHTTPステータスコード(ファイル読み込みエラー:500、検証失敗:400)を返すことです。
私は非標準の特殊化されたcatch
メソッドを使用して解決策を知っていますが、特別な処理が必要です。その意味で、私はエラーを投げたり、エラーオブジェクトに何らかのフィルタリングキーを必要とし、どちらも私の手にはないし、それを達成するための仕事が必要です。このソリューションは、ここで青い鳥ドキュメント&に記載されている:Handling multiple catches in promise chain
これをhttp://stackoverflow.com/questions/26076511/handling-multiple-catches-in-promise-chainの複製としたい方には、他の可能な解決策を知りたい@Esailija(青い鳥の作者)がここで述べた連鎖の終わりにある「キャッチ」のすべてのエラーを処理したくないのです。http://stackoverflow.com/a/26077569/340290 – manikanta
あなたの質問は、答えはおそらく "いいえ、キャッチチェーンを破る方法はありません"です。チェーンの終わりに最終的なキャッチハンドラを使用することに異論はありますか? – CodingIntrigue
最後に 'catch'を使用するには、少なくともフラグを維持するか、エラーオブジェクトを確認してさまざまなエラー状態を知る必要があります。それはif-elseif-elseとなるでしょう。ではない? – manikanta