繁体   English   中英

一个 function 在本地存储中设置项目后调用一个

[英]Call one function after another has set item in local storage

我目前正在尝试根据我的本地存储内容执行两个操作。

我的项目使用 ReactJS 但由于我不知道如何全局设置 state,或者通过父组件和子组件来回传播我的数据,我决定使用本地存储来完成。

我正在尝试为登录用户分配角色和权限。 为了做到这一点,我有两个单独的 fetch 函数,只要我的用户通过身份联合代理身份验证,我就会执行这些函数。

这是我在单独的UserAuthorization.js文件中的第一个 function :

function UserAuthorisation() {
  const userid = localStorage.getItem("userid"); //GETS THE TOKEN SET BY IFB.

  if (userid !== null) {
    fetch("https://api.myjsons.com/binz/examplebin")
      .then(response => response.json())
      .then(response => {
        for (let eachUser = 0; eachUser < response.length; eachUser++) {
          if (userid === response[eachUser].id) {
            localStorage.setItem("role", response[eachUser].role);
          }
        }
      });
  } else {
    console.log("We don't have the user ID item");
  }
}

export default UserAuthorisation;

这是第二个 function 应该在UserAuthorization.js之后运行:

function FetchUserPermissions() {
  const userRole = localStorage.getItem("role");
  console.log(userRole);
  if (userRole !== null) {
    fetch("https://api.myjsons.com/binz/xxzsz")
      .then(response => response.json())
      .then(response => {
        for (let permission = 0; permission < response.length; permission++) {
          if (permission === response[permission]) {
            console.log(response[permission], "<<<<<<< This is the user Role");
            return response[permission];
          }
        }
      });
  } else {
    console.log("not loggedin === no user permissions.");
  }
}

export default FetchUserPermissions;

我遇到的问题是,由于我只是用他们的名字来调用我的函数,第二个FetchUserPermissions打印出null而不是userRole

我认为这是因为我试图在设置之前从本地存储中获取角色,但是当我更改为 function 以异步等待时,我得到了一个结果cannot read property.length of undefined

如何在第一个之后调用我的第二个 function 并从本地存储中获取我的角色元素?

提前为这个愚蠢的问题道歉..

你说得对。 它发生的原因是当 FetchUserPermissions 调用 UserAuthorisation 时无法及时将角色设置到 localStorage。 简单的解决方案是从 UserAuthorisation 返回 Promise 并在 then() 中调用 FetchUserPermissions。

function UserAuthorisation() {
  const userid = localStorage.getItem("userid"); //GETS THE TOKEN SET BY IFB.

  if (userid !== null) {
    return fetch("https://api.myjsons.com/binz/examplebin")
      .then(response => response.json())
      .then(response => {
        for (let eachUser = 0; eachUser < response.length; eachUser++) {
          if (userid === response[eachUser].id) {
            localStorage.setItem("role", response[eachUser].role);
          }
        }
      });
  } else {
    console.log("We don't have the user ID item");
  }

  return Promise.resolve();
}

export default UserAuthorisation;

用法。

UserAuthorisation().then(() => {
  FetchUserPermissions();
});

给你一个小例子。

 function first() { return new Promise((resolve) => { setTimeout(() => { console.log('1'); resolve(); }, 1000); }); } function second() { console.log('2'); } second(); // 2 first().then(second); // 1 -> 2

在此处阅读有关 Promise 的更多信息https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise或在此处https://javascript.info/promise-basics

fetch("https://api.myjsons.com/binz/xxzsz")
  .then(response => response.json())
//here, response.json() will send object in next promises chain.
  .then(response => {
//response.length not working on object.
log your response here & check your condition 
for (let permission = 0; permission < response.length; permission++) 

您可以创建 promise 然后调用 FetchUserPermissions

function UserAuthorisation() {
return new Promise(function(resolve, reject) {
  const userid = localStorage.getItem("userid"); //GETS THE TOKEN SET BY IFB.

  if (userid !== null) {
    fetch("https://api.myjsons.com/binz/examplebin")
      .then(response => response.json())
      .then(response => {
        for (let eachUser = 0; eachUser < response.length; eachUser++) {
          if (userid === response[eachUser].id) {
            localStorage.setItem("role", response[eachUser].role);
            resolve(response[eachUser].role)
          }
        }
      });
  } else {
    reject("We don't have the user ID item")
    console.log("We don't have the user ID item");
  }
});

}

export default UserAuthorisation;


UserAuthorisation.then(FetchUserPermissions(role));

暂无
暂无

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

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