Mazzy Mazzy - 2 months ago 13
Javascript Question

How to promisify correctly JSON.parse method with bluebird

I'm trying to promisify

JSON.parse
method but unfortunately without any luck. This is my attempt:

Promise.promisify(JSON.parse, JSON)(data).then((result: any) => {...


but I get the following error

Unhandled rejection Error: object

Answer

First of all, JSON.parse is not an asynchronous function. So, don't try to promisify it.


Because I want to create a chain of promises where JSON.parse stand at the top

Then, simply create a Promise resolved with the parsed JSON object, like this

Promise.resolve(JSON.parse(data))
    .then(...)

Now, to your actual question, you are getting the error,

Unhandled rejection Error: object

because, if your chain of promises is rejected, you are not handling it. So, don't forget to attach a catch handler, like this

Promise.resolve(JSON.parse(data))
    .then(...)
    .catch(...)

READ THIS There is a problem with the approach I have shown here, as pointed out by Bergi, in the comments. If the JSON.parse call fails, then the error will be thrown synchronously and you may have write try...catch around the Promise code. Instead, one would write it as Bergi suggested in his answer, to create a Promise object with just the data, and then do JSON.parse on that Promise chain.

Comments