1
// foo.json
[]
// bar.json
[
  {
    "name": "bar",
    "type": "whatever" 
  }
]
function getJSON(path) {
  return fetch(`http://localhost:4000/admin/${path}`)
    .then(response => response.json())
}
function getStart() {
  getJSON('foo')
    .then(data => {
      if (data.length == 0) {
        return getJSON('bar')
        // Look at bar.json and access to next .then() method
      }
      console.log('Access Denied')
      // skip the next .then() method and exit.
    })
    .then(data => {
      console.log(data, 'another then path')
    })
}

I added if statement inside of first .then() for giving different path depends on the foo's data.length is 0 or not.

A problem is the code always accesses to the second .then() whatever the boolean is true or false.

This is the result:

Access Denied index.js:31

undefined "another then path" index.js:34

I have found a similar question like me but he uses promise, not fetch, and I don't know how to use reject in fetch clause.

Any tips to fix this problem?

sniffingdoggo
  • 398
  • 4
  • 16

1 Answers1

2

You could use throw for trigger an error in Promise. Example of code :

const promise1 = new Promise(function(resolve, reject) {
  throw 'Uh-oh!';
});

promise1.catch(function(error) {
  console.error(error);
});
// expected output: Uh-oh!

For your code :

function getStart() {
  getJSON('foo')
    .then(data => {
      if (data.length === 0) {
        return getJSON('bar')
        // Look at bar.json and access to next .then() method
      } else {
         console.log('Access Denied');
         throw new Error('Access Denied');
      }
    })
    .then(data => {
      console.log(data, 'another then path')
    })
    .catch(e => {
      console.log('Error', e);
    }
}
SanjiMika
  • 2,664
  • 19
  • 19