0

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

antigirl
  • 63
  • 4

2 Answers2

0

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.

loganfsmyth
  • 156,129
  • 30
  • 331
  • 251
0

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')
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • This form will be deprecated in 3.0 btw : -) – Esailija Apr 14 '15 at 07:04
  • @Esailija: Where can I find information about that? The `API.md` in the `3.0` branch isn't updated yet… Is it that we always need to use arrays? – Bergi Apr 14 '15 at 07:11
  • 1
    It's just awkward. And with arrows only taking a function is not that bad `Promise.try(_ => require('file.json'))` – Esailija Apr 14 '15 at 07:30
  • @Esailija: Hm, I like it. Of course there are alternatives using two calls… – Bergi Apr 14 '15 at 07:40