Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 243
Mazzy Avatar asked Aug 31 '15 10:08

Mazzy


1 Answers

Late to the party, but I can totally understand why you might want a promisified JSON parse method which never throws exceptions. If for nothing else, then to remove boilerplate try/catch-handling from your code. Also, I see no reason why synchronous behavior shouldn't be wrapped in promises. So here:

function promisedParseJSON(json) {
    return new Promise((resolve, reject) => {
        try {
            resolve(JSON.parse(json))
        } catch (e) {
            reject(e)
        }
    })
}

Usage, e.g:

fetch('/my-json-doc-as-string')
  .then(promisedParseJSON)
  .then(carryOn)
  .catch(dealWithIt)
like image 55
mtkopone Avatar answered Oct 07 '22 17:10

mtkopone