Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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

// assume I provide valid raw_input...
console.log(test(raw_input));
// 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 "return" in the function 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...)

ADDING codes (more about raw)

In the function, I am reading json file, then JSON.parse it, then return the result. (source is the path to the json file)

function test(source) {
fs.readFile(source, function (err, content) {
return JSON.parse(content));
});
}
console.log(test('test.json'));
// it says
// undefined

json file looks like this (test.json)

{
"a": "apple",
"b": "banana",
"c": "cat"
}
like image 707
ryan Avatar asked Jan 26 '26 10:01

ryan


1 Answers

JSON.parse() is indeed synchronous, so is console.log(), so is the return statement. Everything in Javscript is synchronous (and single threaded) unless you explicitly make it asynchronous.

You're getting an undefined because the whatever you passed in raw to JSON.parse() wasn't valid JSON or it was empty or maybe it wasn't actually a string.

Here is a live example to show it running synchronously.

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

console.log('this happens first');
console.log(test('{"valid1": true}'));
console.log('this happens 3rd');
console.log(test('{"valid2": true}'));
console.log('this happens last');
like image 50
Soviut Avatar answered Jan 28 '26 23:01

Soviut



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!