How to promisify correctly JSON.parse method with bluebird

Mazzy picture Mazzy · Aug 31, 2015 · Viewed 18.7k times · Source

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

Bergi picture Bergi · Aug 31, 2015

Promise.promisify is thought for asynchronous functions that take a callback function. JSON.parse is no such function, so you cannot use promisify here.

If you want to create a promise-returning function from a function that might throw synchronously, Promise.method is the way to go:

var parseAsync = Promise.method(JSON.parse);
…

parseAsync(data).then(…);

Alternatively, you will just want to use Promise.resolve to start your chain:

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