function readFile(filePath) {
// 模拟异步读取文件,返回Promise
return new Promise((resolve, reject) => {
// 实际实现中使用文件系统相关API读取文件
setTimeout(() => {
if (Math.random() > 0.5) {
resolve('{"key": "value"}');
} else {
reject(new Error('读取文件失败'));
}
}, 1000);
});
}
function parseJSON(jsonStr) {
// 模拟异步解析JSON,返回Promise
return new Promise((resolve, reject) => {
setTimeout(() => {
try {
resolve(JSON.parse(jsonStr));
} catch (error) {
reject(new Error('解析JSON失败'));
}
}, 1000);
});
}
function getSpecificProperty(filePath, property) {
return readFile(filePath)
.then(data => parseJSON(data))
.then(jsonObj => jsonObj[property])
.catch(error => {
console.error('操作过程中出现错误:', error.message);
return null;
});
}
// 使用示例
getSpecificProperty('example.txt', 'key')
.then(value => {
if (value!== null) {
console.log('特定属性值:', value);
}
});