简体   繁体   English

这个'if' JavaScript 语句有什么问题?

[英]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.只有当从 Url 解析的用户当前域匹配时,才应该执行 function 的 rest。 (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.问题是 function 仍在执行,无论用户登陆什么 Url,即使有这个“如果”条件。 I know this because the recommendations api fires regardless of what site I navigate to.我知道这一点,因为无论我导航到哪个站点,建议 api 都会触发。 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. browser.storage.local.get返回一个异步执行的 promise。 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.包含你的return语句的function是在rest o代码块之后执行的,不会对该代码块的rest的执行产生任何影响。 You will need to place the rest of the block in a function and change the code to您需要将块的 rest 放在 function 中并将代码更改为

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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