JSFiddle - React, Tailwind, and code Playground

by Csaba Hellinger

HTML

Make the code below able to handle if the response we get in json is not valid JSON.
<pre>
- If it’s not a valid JSON, or it doesn’t contain the zip code:
  Log “invalid json” and don’t call logZip.
- Valid JSON with the zip code:
  Call logZip.
- In any case:
  Don’t let an unhandled exception escape the promise chain.
</pre>
Check the console for the results.

JavaScript

//const fetchUser = id => Promise.resolve(null);
//const fetchUser = id => Promise.resolve('{"name": "bob"}');
const fetchUser = id => Promise.resolve('{"address": {"zip": 1234}}');

const logZip = zip => console.log('zip', zip);


/*
fetchUser(12)
  .then(json => {
    const user = JSON.parse(json);
    return user.address.zip;
  })
  .then(logZip);
//*/

/*
fetchUser(12)
  .then(json => {
    try {
      const user = JSON.parse(json);
      return logZip(user.address.zip);
    } catch (ex) {
      console.error('invalid json');
    }
  });
//*/

///*
fetchUser(12)
  .then(JSON.parse)
  .then(user => user.address.zip)
  .then(logZip)
  .catch(err => {
    console.error('invalid response');
  });
//*/