Johnson
Johnson

Reputation: 1536

JS Double Fetch condition

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!

Upvotes: 0

Views: 1149

Answers (1)

Bergi
Bergi

Reputation: 665145

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);

Upvotes: 3

Related Questions