问题
If i require a file as
require('file.json');
how do i go about checking if the JSON is valid? try catch? I'm using bluebird promises so right now its just returning
Promise.resolve(require('file.json'));
and bluebird catches if file is not found but i also need to check the JSONs sanity. I understand you can just pass JSON.parse to a thenable if file itself is returned as a string by FS or whatever but i dont mind caching and requiring would be faster
回答1:
You are looking for the Bluebird try function. If you use resolve
, the require()
call may throw before its result is wrapped in a promise.
Promise.try(require, 'file.json')
Promise.try(() => require('file.json')) // Bluebird 3.0
Alternatively use
Promise.resolve('file.json').then(require)
// or
Promise.method(require)('file.json')
回答2:
The issue with
Promise.resolve(require('file.json'));
is that it runs as
var obj = require('file.json');
Promise.resolve(obj);
which means that if the require
throws, the promise has no way to catch it. Instead, I'd recommend doing
new Promise(function(resolve){
resolve(require('file.json'));
})
This executes require
from inside a promise, so the thrown error will be caught properly.
来源:https://stackoverflow.com/questions/29615098/check-if-required-json-is-valid-node