在promise链中创build错误

我将如何检查一个属性的JSON,如果它缺less返回一个错误退出和捕捉链?

var Promise = require("bluebird"); var fs = Promise.promisifyAll(require("fs")); fs.readFileAsync("myfile.json").then(JSON.parse).then(function (json) { if (!json.prop) return new Error("missing prop"); return json; }).catch(SyntaxError, function (e) { console.error("file contains invalid json"); }).catch(Promise.OperationalError, function (e) { console.error("unable to read file, because: ", e.message); }); 

从蓝鸟文件取得的例子。

你可以使用typeof操作数,捕获undefined和像其他错误一样抛出/ catch,特别是你可以在你的情况下使用ReferenceErrortypes:

 fs.readFileAsync("myfile.json").then(JSON.parse).then(function (json) { if (typeof json.prop === "undefined") throw new ReferenceError("missing prop"); return json; }).catch(SyntaxError, function (e) { console.error("file contains invalid json"); }).catch(Promise.OperationalError, function (e) { console.error("unable to read file, because: ", e.message); }).catch(ReferenceError,function(e){ //handle the error });