$.getJSON(url, function(json) {
for (var i in json) {
if (json[i].emaill == userMail) {
role = data[i].role
}
}
return role
});
i need to pass role variable to the another function
$.getJSON(url, function(json) {
for (var i in json) {
if (json[i].emaill == userMail) {
role = data[i].role
}
}
return role
});
i need to pass role variable to the another function
Regardless of where you want the data, you first need to understand how javascript handles asynchronous code (and what that means for YOU, the developer) Because $.getJSON is asynchronous, doing something like return role
will not do anything useful in your regular idea of how functions return values. Something introduced recently is await/async which attempts to abstract away a lot of this code. However, this also comes with some caveats. What I would do is use async/await to make things a lot more simple. I would use fetch:
async function getUserRole (userEmail) {
const response = await fetch(url);
const json = await response.json();
let role;
json.forEach(user => {
if(user.email === userEmail) {
role = user.role;
}
}
return role;
}
Because of the await
keyword before the fetch
and response.json()
the javascript engine will not move onto the next line even though these are asynchronous calls. This makes the code behave more like you would expect. Then after we get the json data, we can iterate over each element with the array function forEach
and set the role based on the passed in userEmail
. Do note however, that you see the async
declaration before the function? That is required anytime you use await. This means that you will also need to decorate the function that is calling getUserRole
with async
as well.
$.getJSON(
url,
[data],
[callback] //Do what u want
)
Process the role in callback