0

I'm working in get a list from a local file. But the folder sometimes can change. So come here to ask you guys if it's correct, because I think there is a better way to do it, idk. Please help me :)

  fetch("./myJson.json")
     .then(res => { 
        if(res.status != 404)
           res.json() 
        else
           fetch("../myJson.json")
              .then(res => res.json())
              .then(data => console.log(data))
              .catch(err => console.error(err));
     })
     .then(data => console.log(data))
     .catch(err => console.error(err));

Thanks!

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Johnson
  • 1,396
  • 6
  • 17
  • 36

1 Answers1

3

You will need to return the nested promises from the callback and use the promise chaining feature:

fetch("./myJson.json").then(res => { 
    if (res.ok)
        return res.json() 
    else
       return fetch("../myJson.json").then(res => res.json());
}).then(console.log, console.error);
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Nice Bergi!! Thanks!! Just a detail... If the first fetch fails, an error 404 shows up in console. Can I tell him that "if the first fetch fails, the second one will solve it. You don't have to show any error in console about this first fetch." – Johnson Nov 24 '18 at 16:39
  • 1
    The 404 will always show up in the console, you cannot prevent that from JS. You will need to use [different console settings](https://stackoverflow.com/questions/4500741/suppress-chrome-failed-to-load-resource-messages-in-console). Or actually handle the logic on the server side with a redirect. – Bergi Nov 24 '18 at 16:48