Mongoose callback not firing - javascript

This is the function in question
function matches_password(password)
{
var modified = false;
var matched = false;
User.count({password : password}, function (err, result)
{
modified = true;
console.log('hei');
if (err)
{
//error
}
else
{
if (result)
{
matched = true;
}
}
});
while (!modified)
{
console.log('sleeping');
sleep.usleep(100000);
}
return matched;
}
As you can see, I have a callback that updates some variables; the main flow of execution is delayed until the callback is fired. The problem is that 'hei' never appears in the console.
Removing the while loop fixes the problem, but I need it, or else matched is always false.
What's going on and what can I do to get around this setback?

It looks like you're running into a asynchronous issue. you could try using a setTimeout function inside your while loop that calls User.count(...)
for how setTimeout works with Node: How does setTimeout work in Node.JS?

Related

Javascript Callback Not Working as Intended

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.

Parellel.js doesn't work

I am trying to use Parallel.js (http://adambom.github.io/parallel.js/) in my code
In the html page the parallel.js script then in my code I placed these lines
parallelStarts = true;
var parallel = new Parallel(this.chromosomes, {
maxWorkers: 4,
evalPath: 'js/eval.js',
env: {
state: pslg.state,
totalDiffLevels: pslg.LevelGenerator.levelsOutline.length
}
});
parallel.map(function(chromosome) {
chromosome.CalculateFitness(global.env.state, global.env.totalDiffLevels);
return chromosome;
}).then(function(res) {
parallelStarts = false;
}, function(res) {
console.logError("Parallelism Failed");
});
while (parallelStarts) {}
I tried everything and nothing happens the function is not called by anything because it never change the parallelStarts variable to false.
Any help?
It's look like that infinite loop block all.
I suggest that use setInterval() or setTimeout() to check if parallelStarts variable changed his value, instead of infinite loop.

Returning from a parent function from inside a child function - Javascript

I'm relatively new to coding in JavaScript, and I've came across a problem. I like to nest functions to keep things orderly, but how would I exit from a parent function from inside a child function?
example:
function foo1() {
function foo2() {
//return foo1() and foo2()?
}
foo2();
}
See update under the fold
You can't. You can only return from the child function, and then return from the parent function.
I should note that in your example, nothing ever calls foo2 (As of your edit, something does). Let's look at a more real example (and one that comes up a lot): Let's say we want know if an array contains an entry matching some criterion. A first stab might be:
function doesArrayContainEntry(someArray) {
someArray.forEach(function(entry) {
if (entryMatchesCondition(entry)) {
return true; // Yes it does <-- This is wrong
}
});
return false; // No it doesn't
}
You can't directly do that. Instead, you have to return from your anonymous iterator function in a way to stop the forEach loop. Since forEach doesn't offer a way to do that, you use some, which does:
function doesArrayContainEntry(someArray) {
return someArray.some(function(entry) {
if (entryMatchesCondition(entry)) {
return true; // Yes it does
}
});
}
some returns true (and stops looping) if any call to the iterator function returns true; it returns false if no call to the iterator returned true.
Again, that's just one common example.
You've referred to setInterval below, which tells me that you're almost certainly doing this in a browser environment.
If so, your play function almost certainly has already returned by the time you want to do what you're talking about, assuming the game has any interaction with the user other than alert and confirm. This is because of the asynchronous nature of the environment.
For example:
function play() {
var health = 100;
function handleEvent() {
// Handle the event, impacting health
if (health < 0 {
// Here's where you probably wanted to call die()
}
}
hookUpSomeEvent(handleEvent);
}
The thing is, that play will run and return almost immediately. Then the browser waits for the event you hooked up to occur, and if it does, it triggers the code in handleEvent. But play has long-since returned.
Make a note whether the parent function should also return.
function foo1() {
bool shouldReturn = false;
function foo2() {
shouldReturn = true; // put some logic here to tell if foo1() should also return
return;
}
if (shouldReturn) {
return;
} else {
// continue
}
}
It only says that you can't return the parent function in the child function, but we can do a callback and make it happen.
function foo1(cb = () => null) {
function foo2() {
cb();
}
foo2();
}
foo1(() => {
// do something
});
We can use Promises for this:
const fun1 = async () => {
const shouldReturn = await new Promise((resolve, reject) => {
// in-game logic...
resolve(true)
})
if(shouldReturn) return;
}
if you wanna return from the parent function, then just resolve with true
Based on your comment, something like this might work as a main game loop.
function play() {
var stillPlaying = true;
while(stillPlaying) {
... play game ...
stillPlaying = false; // set this when some condition has determined you are done
}
}

Execute statement after return statement in Javascript

window.onbeforeunload = function() {
if (document.getElementById("parentpan").style.display == "block") {
return "You are logged out.";
Logout();
}
};
I want the logout() function to be called after the return statement, is it possible?
You can't execute anything after a return statement.
edit: the finally statement allows code execution after a return for cleanup purposes.
(This is a good example for an XY-Question: You are asking about Y while never telling us for what X you actually need it).
The best possible way and most efficient way is try, catch and finally
catch is optional in this
`try{
// do something
return;
} finally {
// call function after return
}`
https://youtu.be/Is_o_L-ZIS8 this is helpful for you
The return statement ends a function, you cannot execute code after it. You could do this:
ret = "You are logged out.";
Logout();
return ret;
What you need is to execute Logout asynchronously. This can be easily achieve in JavaScript by using the setTimeout function as others have said. Here's a method I commonly use to call functions asynchronously:
Function.prototype.async = function () {
setTimeout.bind(null, this, 0).apply(null, arguments);
};
This method pushes a function call onto the event loop immediately (after 0 ms). Hence the function is executed after the current code completes (which for you is after you return). Here's a simple example of how to use it:
alert.async("This will be displayed later.");
alert("This will be displayed first.");
Since the first alert is called asynchronously it will execute after the second call to alert. As simple as preceding your function call with async. This is what you would do in your case:
window.onbeforeunload = function () {
if (document.getElementById("parentpan").style.display === "block") {
Logout.async();
return "You are logged out.";
}
};
What's the disadvantage? Since the function is blocked on the event loop it may never get the chance to execute (hence the user will never logout). Such a situation may arise. It usually occurs when the control goes into an infinite loop, or hangs because of a blocking AJAX request.
Good news for you however, this happens on a very rare occasion. So don't worry about it. Just use setTimeout like everyone else is bantering you to and you'll do just fine. Personally I think you should log out before returning a message that "You are logged out.", but it's your application.
Happy New Year. Cheers!
In general if you want something to be executed after the function has returned, you can set a timer:
function myFunction() {
if (document.getElementById("parentpan").style.display == "block") {
setTimeout(Logout, 50); // Logout will be called 50ms later
return "You are logged out.";
}
};
However, as noted in comments, this is not a good idea for onbeforeunload, as the timer event will not be fired if the page finished unloading first.
Most of the other answerers are missing what you are trying to do here. You want window.onbeforeunload to act like window.confirm(). There is no way to act on the ok action in the onbeforeunload event.
What you would have to do is hook it up on onunload to do the action.
window.onbeforeunload = function () {
return "Your session will be logged out"
};
window.onunload = function () {
logout();
}
Problem with this is modern day browsers will kill a lot of processes that run in unload/beforeunload to "speed up" the browser so it is faster. So if it is asynchronous, you will have a race condition.
return means you are returning from the execution of the called function.When return statement is executed, system understands that the function execution is over and it will switch to the main program from which the function is called.
In the program, you can see a statement after return.But the system wont check that even.
If you have jquery in your project you can use defered mechanism. You can return promise object for ongoing tasks like this :
function task() {
var defered = $.Deferred();
setTimeout(defered.resolve , 5000);
return defered.promise();
}
function task2() {
var defered = $.Deferred();
setTimeout(defered.resolve , 10000);
return defered.promise();
}
function run() {
return $.when(task(),task2());
}
var promise = run();
promise.done(function(){
alert("All tasks has been completed");
});
Demo
You can use setTimeout to achieve this. Your code should be as below
window.onbeforeunload = function() {
if (document.getElementById("parentpan").style.display == "block") {
setTimeout(function(){
Logout();
}, 0);
return "You are logged out.";
}
};
This will make sure that Logout is executed after return statement.
var a = 10;
function b(){
a = 25;
return;
function a(){}
}
b();
document.write(a);
try it
I found two ways to approach this.
The first one is as stated above by Bhavsar Japan
1. Example with try, catch and finally
const example1 = () => {
try {
return console.log('will execute first')
} finally{
console.log('will execute second')
}
return 'will never execute'
}
const main = () => {
const message = example1();
console.log(message)
}
main()
2. Example with Promise.resolve
const example2 = () => {
Promise.resolve()
.then(() => console.log('will execute after return'));
return 'will execute first'
}
const main = () => {
const message = example2();
console.log(message);
}
main();
I just written a way to return a result and then call a callback, like this:
function after_return(result, callback) {
function returner(resolve) {
if (!resolve) {
new Promise((res) => returner(res)).then(callback);
return result;
} else {
resolve();
}
}
return returner(undefined);
}
function main(a, b) {
return after_return(a + b, (_) => {
console.log("DONE");
});
}
console.log(main(5, 4));
I'm guessing that Logout is a time-intensive process and you want to provide feedback to the user before executing it:
setTimeout(Logout,1);
return "You are logged out.";

Phonegap wait for database transaction to complete

I'm creating a Phonegap application that will perform differently on first run. The way that I am detecting the first run is by seeing of one of the database tables exists. As you can probably tell from the code below, I am checking for the error that is (probably) indicating that the table already exists, thus proving that this is not the application's first run.
function databaseExists(){
var exists;
database.transaction(function(tx){
tx.executeSql('CREATE TABLE GLOBAL (uid, property, value)');
}, function(err){
exists = true;
}, function(){
exists = false;
});
return exists;
}
My problem, however, is that the asynchronous execution of the Javascript code means that the function returns its value before the success (or error) function has set it's value.
This function is called in the initialising stage of the application:
if (databaseExists()){
// Do Something
}
And therefore must return the value rather than execute the function in the success callback of the transaction.
Is there a way to force the execution to wait until the database transaction is complete or return the value through the database.transaction object?
Thanks in advance,
Jon
You need to write it in callback form:
var dataBaseExists(yep, nope) {
database.transaction(function(tx) {
tx.executeSql('CREATE TABLE GLOBAL (uid, property, value)');
}, function(){
if (yep) {
yep.apply(this, arguments);
}
}, function(){
if (nope) {
nope.apply(this, arguments);
}
});
};
var itDoes = function() {
console.log("great");
};
var itDoesNot = function() {
console.log("what a pity");
};
databaseExists(itDoes, itDoesNot);
You need callbacks, but if don't need checking existment of your tables, you can do that easily with localStorage.
e.g.
if(localStorage.getItem('init') === null){
//init
localStorage.setItem('init', true);
}
You will avoid dealing with database.
and maybe this gonna be helpful "CREATE TABLE IF NOT EXISTS..."
I know there's gonna be programmers don't like my solution, but I love it!
var myfEspereti=false;
function Espereti(pStatus)
{
if (pStatus==="wait")
{
myfEspereti = true;
while(myfEspereti)
{
}
}
else if (pStatus==="go")
{
myfEspereti=false;
}
}
and then call Espereti ("wait") when you want to wait for an async call. Inside the async call, when it's finish, call Espereti ("go") and that's it!

Categories