简体   繁体   中英

What is wrong with this 'if' JavaScript statement?

I didn't write this originally, so I apologize for gaps in my knowledge.

I've added the following block of code to determine if a user has navigated to one of the domains contained in an array. This array is defined as 'domains.' Only if the user's current domain, parsed from Url, is a match, should the rest of the function be executed. (my addition starred).

The problem is that the function is still executing regardless of what Url the user lands on, even with this 'if' condition in place. I know this because the recommendations api fires regardless of what site I navigate to. I'm not sure it's a placement issue or if my syntax is incorrect (or both); but I'd greatly appreciate any insight on this!

export const getRecommendations = url =>

**browser.storage.local.get("domains").then(({ domains }) => {
  const domain = parseDomain(url);
  if (!domains.includes(domain)) { 
    return 
  }
});**


  browser.storage.local.get("user").then(({ user }) =>
  
    fetch(trestle.api.recommendations, {
      method: "POST",
      body: JSON.stringify({ currentUrl: url, emailAddress: user.username }),
      headers: {
        Authorization: `Bearer ${user.token}`,
        Accept: "application/json",
        "Content-Type": "application/json"
      }
    })
      .then(response => response.json())
      .then(recommendation => recommendation)
      .catch(e => new Error("Unable to return recommendations for company"))
  );

browser.storage.local.get returns a promise that is executed asynchronously. The function that contains your return statement is executed after the rest o the block of code and can not have any influence of the execution of the rest of this block. You will need to place the rest of the block in a function and change the code to

browser.storage.local.get("domains").then(({ domains }) => {
  const domain = parseDomain(url);
  if (domains.includes(domain)) { 
    callUrlFunction();
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM