Monday 5 June 2017

How to make JSON.parse promise? (or asynchronous)

I am trying to make a function which returns result of JSON.parse. Following is example code:

function test(raw) {
 return JSON.parse(raw);
}

console.log(test(raw));
// expect json object but it says "undefined"...

I think I know why (please correct me if I am wrong). JSON.parse is not asynchronous... it returns its result when it is ready. And console.log doesn't wait for its result... more like console.log thinks it is done, so it says "undefined".

Here is my question... how can you make JSON.parse promise? Or asynchronous? Like how can you make it to wait result of JSON.parse?

If you can provide simple promise codes... that would be really helpful. Thank you so much in advance. (I am open to bluebird js or async/await or etc...)



via ryan

No comments:

Post a Comment