M4V3N
M4V3N

Reputation: 629

TypeError: (intermediate value)(...) is undefined in selfinvoked function

So I read after this error and apparently there is a semicolon missing? But I simply can't figure out where exactly:

 <script>
  (() => {
    fetch('/testmode')
      .then(response => {
        return response.json();
      }).then(body => {
        console.log('testmode:', body);
        if (body) {
          document.querySelector("link[rel='shortcut icon']").href = "favicon.test.ico";
        } else {
          document.querySelector("link[rel='shortcut icon']").href = "favicon.ico";
        };
    });
  })().catch(err => {
    console.log(err);
  });
  </script>

I placed the semicolon almost everywhere already to find out where it could be missing but I just won't work.

Any idea what I am missing here? Funnily enough when I write async ()... then the error disappears but I can't use async as it's not supported by all browsers.

thanks

Upvotes: 0

Views: 2263

Answers (1)

Bergi
Bergi

Reputation: 665545

No, there's no semicolon missing. You've just misplaced the catch invocation, it should go directly on the promise chain:

fetch('/testmode').then(response => {
  return response.json();
}).then(body => {
  console.log('testmode:', body);
  document.querySelector("link[rel='shortcut icon']").href = body
    ? "favicon.test.ico"
    : "favicon.ico";
}).catch(err => {
  console.log(err);
});

You don't even need the IIFE here - there are no local variables to be protected. If you still want to use one, either wrap the whole thing:

(() => {
  fetch('/testmode').then(response => {
    return response.json();
  }).then(body => {
    console.log('testmode:', body);
    document.querySelector("link[rel='shortcut icon']").href = body
      ? "favicon.test.ico"
      : "favicon.ico";
  }).catch(err => {
    console.log(err);
  });
})();

or return the intermediate value:

(() => {
  return fetch('/testmode').then(response => {
//^^^^^^
    return response.json();
  }).then(body => {
    console.log('testmode:', body);
    document.querySelector("link[rel='shortcut icon']").href = body
      ? "favicon.test.ico"
      : "favicon.ico";
  });
})().catch(err => {
  console.log(err);
});

Upvotes: 1

Related Questions