87,910
社区成员
发帖
与我相关
我的任务
分享
var file = './1.txt';
var fs = require('fs');
function asyncFunction() {
return new Promise(function (resolve, reject) {
fs.readFile(
file, function (err, text) {
if (err) {
console.log(err);
reject("spwan some errors when read " + file);
}else{
console.log("======33333");
//这里的json文件是错误格式,抛出异常,但是没有进入catch中
obj = JSON.parse(text);
console.log("=====44444");
resolve(text);
}
});
})
}
asyncFunction().catch(function (error){
console.log("1123");
}).then(function (text){
console.log("enter asyncFunction");
}).catch(function (error) {
console.log("===error===");
});
asyncFunction().catch(function (error){
console.log("1123");
}).then
当文件存在的时候,json文件是个非法格式的内容, JSON.parse抛出异常,但是并不会进入catch,
你可以试试。
看到没有,我在then的前面插入了一个catch,就是为了捕捉那个JSON.parse,结果捕捉不到。
(new Promise(function(resolve,reject){
JSON.parse('{a:1');
}))
.catch(function(e){
console.log(1);
})
.then(function(){
JSON.parse('{a:1');
})
.catch(function(){
console.log(2);
})
chrome下1 2都会打出var fs = require('fs');
var file = './1.txt';
function asyncFunction() {
return new Promise(function (resolve, reject) {
fs.readFile(
file, function (err, text) {
if (!err) {
console.log("===123===");
console.log("====456===");
JSON.parse(text);
resolve(text);
}else{
reject(text);
}
});
})
}
asyncFunction().then(function (text){
console.log("text:" + text);
}
).catch(function (error) {
console.log("===enter catch===");
console.log(error);
});
两个问题:
问题1:
最后一个then ,也就是
then(function (text){
console.log("text:" + text);
}
里能否返回return new Promise(function (resolve, reject) {}
??
问题2:
如果函数asyncFunction在解析JSON的时候,抛出异常来(比如json是非法格式),我做过实验,异常不会进入 catch中,
请问,我是否应该在asyncFunction 这个里对JSON.parse(text); 进行try ...catch...操作?