I didn't really understand the callback function, and this might be the source of the problems I got:
I have a getCookies() function and it worked, but now I moved it in the background.js and the variable outside the function is still undefined.
Just take a look:
function getCookies(domain, name, callback) {
chrome.cookies.get({"url": domain, "name": name}, function(cookie) {
if(callback) {
callback(cookie ? cookie.value : null);
}
});
}
var upw; //Passwort HASH
//USER PW Hash auslesen
getCookies("http://example.org/", "upw", function(id) {
if(id == null) {
upw= null;
}
else { upw = id;}
console.log("Func: "+upw);
});
console.log("Outside: "+upw);
The console will give me something like this:
Outside: undefined
Func: 1234asdfqwertz5678
So the function will be exectued "too late". I don't know why and I don't know, how to solve this question!
The callback function is asynchronous, so it can't work! I'm handling everything in the Callback function.
Related
I am trying to ensure that checkteamexists only executes after checklogin has executed. However, checkteamexists still functions after checklogin.
You can imagine teamhome1_message and teamhome2_message as alert dialogs. They pop a message up and didn't return anything.
function pushhistory(url, callback) {
history.push(url);
callback();
}
function checklogin(callback) {
if (!state.user.authenticated) {
pushhistory("/accounts/login", function() {
teamhome2_message()
});
}
callback();
}
function checkteamexists(teamname) {
if (teamname.toString().toLowerCase() == "team1") {
teamid = 1;
}
else {
pushhistory("/", function() {
teamhome1_message()
});
}
}
useEffect(() => {
checklogin(function() {
checkteamexists(teamname);
})
}, []);
checklogin worked because the URL became /accounts/login and prompted teamhome2_message. However, teamhome1_message still appeared even though I don't want it to.
I tried specifying a callback in the useEffect hook (which is specific to React) but the callback didn't seem to work either. Can anyone please point out the problem?
Thanks in advance.
#p2pdops had the right solution: put the callback function in the else block.
I have a function that I'm calling. Called getStatus(). But this function requires there to be a defined SessionStorage variable that could be present. If the variable is present then I want to go ahead and execute the getJob() function. If it's not present I want to try to define the SessionStorage variable and then execute the getJob() function.
Like this:
function getStatus()
{
if (sessionGet("jwt") != null)
{
getJob(document.getElementById('job').value, document.getElementById('id').value);
}
else
{
var myValue = '{{ myValue }}';
console.log("Token is missing, acquiring another one!");
var nextToken = setTimeout(function(){ getSessionToken(myValue); }, 5000);
console.log("Reissued token issued is");
console.log(nextToken);
getJob(document.getElementById('job').value, document.getElementById('id').value);
}
}
And here is the function that reads the SessionStorage variable:
function sessionGet(key) {
let stringValue = window.sessionStorage.getItem(key)
if (stringValue !== null) {
let value = JSON.parse(stringValue)
let expirationDate = new Date(value.expirationDate)
if (expirationDate > new Date()) {
return value.value
} else {
window.sessionStorage.removeItem(key)
}
}
return null
}
When I look at the Chrome console I see the SessionStorage variable being written, but the getJob() function that reads the variable doesn't see it. If I retry then the getJob() function is able to read it. My thought is that the getJob() function is firing before the variable has been written. That's why I tried the setTimeout() in there.
Any suggestions?
As ztadic91 pointed out, I needed to wrap the setTimeout around the getJob() function call, since it needed to wait for the SessionStorage variable to be created. After doing that things tested out fine. Appreciate the quick assist!
I am trying to understand a JavaScript code.
Banana.reloadUser is being called inside a function without any arguments:
function(data) {
if (!data.result.success) {
alert(data.result.message)
} else {
/*do something*/
Banana.testData = data;
Banana.reloadUser();
}
}
Banana.reloadUser defined like this:
Banana.extend({
reloadUser: function(cb, data) {
var that = this,
done = function(d) {
$.extend(that.user, d);
if ($.isFunction(cb)) {
cb(d)
}
that.trigger("user.reloaded", [d])
};
if (data) {
done.apply(banana, [data])
} else {
/*do something*/
}
}
})
'reloaduser' is being called to save the userinfo data in the localstorage. So whenever user do something new from its account 'reloaduser' saves the new information into the localstorage.
My question is since Banana.reloadUser is being called without arguments how is it supposed to pick its arguments ?
Note: This is a part of a big JavaScript/jquery code so in case this information is not enough please ignore the question.
The big Javascript code does contain another function
Banana.reloadUser(function() {
try {
Banana.trigger('start', [$]);
}catch(e) { }
try {
$('[data-deferred]').deferredImage();;
}catch(e) { }
});
started = true;
};
If you call a JavaScript function without arguments then all its parameters receive a value of undefined (not null which is a different value).
So calling
Banana.reloadUser()
is just the same as:
Banana.reloadUser(undefined, undefined)
In your code this is perfectly ok, the condition:
if ($.isFunction(cb)) {
will fail because undefined is not a function, and later on the condition:
if (data) {
will also fail because undefined is treated as equivalent to false when it appears somewhere that a boolean value is expected.
It is exactly similar to the below call,
Banana.reloadUser(undefined,undefined);
Can someone please explain to me what is wrong with my code below? I am declaring a public variable and setting it to a setTimeout, and if not null, clearing the timeout before it gets set again. When I try to clear the timeout I get undefined so the timeout continues to run.
var usernameCheckTimeout = null;
$(document).ready(function(){
$("#username").on("keyup", function(e){
if($(this).val().length >= 6)
{
if(usernameCheckTimeout != null)
{
clearTimeout(usernameCheckTimeout);
}
usernameCheckTimeout = setTimeout(isUsernameAvailable($(this).val()), 1000);
}
});
});
function isUsernameAvailable(username)
{
$.ajax({
url : "/account/username-check",
method : "POST",
dataType : 'json',
data : {
'username' : username
}
}).done(function(data) {
console.log(data);
});
};
You do not need to do the null check also you need to create a closure around this, otherwise this will refer to not what you think this actually is.
var usernameCheckTimeout;
$("#username").on("keyup", function (e) {
if ($(this).val().length >= 6) {
clearTimeout(usernameCheckTimeout);
var that = this;
usernameCheckTimeout = setTimeout(function () {
isUsernameAvailable($(that).val();
}, 1000);
}
});
Some jsfiddle love like usual.
The timeout is being cleared. The problem is that you are calling your function immediately instead of passing the function to setTimeout.
setTimeout(isUsernameAvailable($(this).val()), 1000);
isUsernameAvailable($(this).val()) will be called and the result of this call will be passed to setTimeout.
You should instead pass a function which calls this function:
EDIT: As #Mark said, you also need to deal with this not being what you expect:
var value = $(this).val();
setTimeout(function(){
isUsernameAvailable(value)
}, 1000);
You have a couple of issues. The first issue, which is huge, is that you are executing isUsernameAvailable($(this).val()) immediately and passing the return value to setTimeout - you need to move this into an anonymous function so it does not execute until the anonymous function is called by the timeout:
usernameCheckTimeout = setTimeout(function () {
isUsernameAvailable($(this).val());
}, 1000);
the javascript timeout functions rely on numeric IDs to function. You should avoid testing for null or undefined or anything else, and instead test for a number:
// leave it as undefined
var usernameCheckTimeout;
...
if (typeof usernameCheckTimeout === 'number') {
clearTimeout(usernameCheckTimeout);
}
Ok so lets say I have this function:
function a(message) {
alert(message);
}
And I want to have a callback after the alert window is shown. Something like this:
a("Hi.", function() {});
I'm not sure how to have a callback inside of the function I call like that.
(I'm just using the alert window as an example)
Thanks!
There's no special syntax for callbacks, just pass the callback function and call it inside your function.
function a(message, cb) {
console.log(message); // log to the console of recent Browsers
cb();
}
a("Hi.", function() {
console.log("After hi...");
});
Output:
Hi.
After hi...
You can add a if statement to check whether you add a callback function or not. So you can use the function also without a callback.
function a(message, cb) {
alert(message);
if (typeof cb === "function") {
cb();
}
}
Here is the code that will alert first and then second. I hope this is what you asked.
function basic(callback) {
alert("first...");
var a = "second...";
callback(a);
}
basic(function (abc) {
alert(abc);
});