Search code examples
javascriptnode.jsasynchronouspromisebluebird

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

Solution

  • 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(…);