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
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
Promise.promisify
is thought for asynchronous functions that take a callback function.JSON.parse
is no such function, so you cannot usepromisify
here.If you want to create a promise-returning function from a function that might
throw
synchronously,Promise.method
is the way to go:Alternatively, you will just want to use
Promise.resolve
to start your chain:First of all,
JSON.parse
is not an asynchronous function. So, don't try to promisify it.Then, simply create a Promise resolved with the parsed JSON object, like this
Now, to your actual question, you are getting the error,
because, if your chain of promises is rejected, you are not handling it. So, don't forget to attach a catch handler, like this
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 to writetry...catch
around thePromise
code. Instead, one would write it as Bergi suggested in his answer, to create a Promise object with just the data, and then doJSON.parse
on that Promise chain.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:
Usage, e.g: