JS init function not waiting for another function to completed - javascript

In my JS I want to wait for this fnDocumentTypeCount to be compelted before I go into the other with the logic for the init but it will not wait for that function to be completed.fnDocumentTypeCount is a $.ajax that I was going to return a number.
init: function () {
var countType = fnDocumentTypeCount(GroupId);
console.log(countType);
}

Use await:
init: async function () {
var countType = await fnDocumentTypeCount(GroupId);
console.log(countType);
}
Or here's the old way of doing this:
init: function () {
fnDocumentTypeCount(GroupId).then(countType => {
console.log(countType);
});
}

Related

Javascript: TypeError: callback is not a function

Pulling my hair out here trying to understand the infuriating nuances of Javascript. Hopefully some JS guru can take a gander, point and go, "well, there's yer problem...".
Here's a slimmed down sample of the problem:
var Parent = (function () {
var func1 = function () {
func2(function (res) {
console.log(res);
});
};
var func2 = function (callback) {
callback('abc');
};
return {
init: function () {
func1();
func2();
}
};
})();
Call with Parent.init();
This fails with the error:
Uncaught TypeError: callback is not a function
at check2 (<anonymous>:9:9)
at Object.init (<anonymous>:15:13)
at <anonymous>:1:8
What's getting me, is that if I comment out the enclosing code, like so, then it works as expected:
// var Parent = (function () {
var func1 = function () {
func2(function (res) {
console.log(res);
});
};
var func2 = function (callback) {
callback('abc');
};
// return {
// init: function () {
// func1();
// func2();
// }
// };
// })();
...and call with func1();
Result:
abc
What am I missing?
Thanks
In your version, you're calling func2() without specifying the callback function, which is a required argument. In your second example (with init commented out), you're correctly specifying the callback function in func2(function (res) { ... });.
Is the below snippet something you're looking for?
const Parent = (function () {
const func1 = function () {
func2(function (res) {
console.log(res);
});
}
const func2 = function (callback) {
callback('abc'); // this is passing 'abc' to line 3 of this snippet
}
return {
init: function () {
func1();
// func2(); // you don't want to call "func2" here, as "func1" calls it
// Or you could run:
func2(function (res) {
console.log(res);
});
// But this makes "func1" redundant
}
};
});
Parent().init();
// Output
abc
You have to pass callback parameter into func2 inside init. something like this.
init: function () {
func1();
func2(function (res) {
console.log(res);
});
}
From a comment on the question:
I just want to know why it works in the one sample, but not the other.
Because in one example you pass an argument to func2 and in the other you don't. Look at the working version:
func2(function (res) {
console.log(res);
});
vs. the non-working version:
func2();
The difference is that the first one passes a function which gets invoked as callback('abc'); whereas the second one passes nothing, so the attempt to invoke the non-existant callback function fails.
As an aside, in your non-working example you call func2 twice, once with the callback and once without. So it both "works" and "fails" in that case.

javascript callback - execution of scripts is in random order

I have this problem - while executing this function
function(){
var after = function(){
server.executescript("scriptname")
};
var before = function (callback) {
server.executescript("scriptname2")
callback();
};
before(after);
}
execution of scripts is in random order and not as I would expect:
scriptname2
scriptname
what am I missing?
Thank you!
this seems to work
function(){
function after(){
server.executescript("scriptname");
}
function before(){
return new Promise((resolve, reject)=>{
server.executescript("scriptname2");
resolve();
});
}
before().then(after);
}
thank you all for participating!
The order you are seeing is the one expected:
var after = async function() {
await console.log("scriptname");
};
var before = async function (callback) {
await console.log("scriptname2");
callback();
};
before(after);
You first call the "before()" function which is going to call your "scriptname2".
Then you will call your "callback()" which is your "after()" function.
Which is going to call your "scriptname".

False positive unit test result

I have notice that unit testing in javascript and its frameworks is very painful. Many fail positive results. I.e
it('should call Event.create when all if ok', function () {
EventsPersistancyService.accept(message).then(function () {
sinon.assert.calledOnce(s3);
done();
});
});
EventsPersistancyService:
var EventsPersistancyService = {
accept: function acceptService(msg) {
var worker_id = WorkerCacheService.get('some login');
var app_category = AppCategoryService.get('some');
Event.create('msg'); <------------ **first**
var p = Q.all([worker_id, app_category]).then(function () {
var content = msg.content.toString();
content = JSON.parse(content);
var tmp = {};
return Event.create('msg'); <------ **second**
});
return p;
}
}
In that example test pass but it shouldn't. What am I doing wrong?
For starters, you never defined the done callback in your callback to it. But for promises, it is better to return the promise in your test, mocha will wait for promises to resolve.
it('should call Event.create when all if ok', function () {
return EventsPersistancyService.accept(message).then(function () {
sinon.assert.calledOnce(s3);
});
});
A working example with your done callback (note the done declaration as function argument):
it('should call Event.create when all if ok', function (done) {
EventsPersistancyService.accept(message).then(function () {
sinon.assert.calledOnce(s3);
done();
});
});

Write a library in javascript that can run asynchronous functions sequentially

I want to write a library in javascript that can run the code like this:
seq.next(function(done){
setTimeout(done,3000);
}).next(function(done){
setTimeout(function(){
console.log("hello");
done();
},4000);
}).end(); //.next morever
Actually I want to write a library that can excecute asynchronous functions in order(sequentially). Each asynchronous function should run the "done" function on its end.
Could anyone please help me. Thanks very much!
The library is:
var seq = (function () {
var myarray = [];
var next = function (fn) {
myarray.push({
fn: fn
});
// Return the instance for chaining
return this;
};
var end = function () {
var allFns = myarray;
(function recursive(index) {
var currentItem = allFns[index];
// If end of queue, break
if (!currentItem)
return;
currentItem.fn.call(this, function () {
// Splice off this function from the main Queue
myarray.splice(myarray.indexOf(currentItem), 1);
// Call the next function
recursive(index);
});
}(0));
return this;
}
return {
next: next,
end: end
};
}());
And the use of this library is sth like this:
seq.next(function (done) {
setTimeout(done, 4000);
}).next(function (done) {
console.log("hello");
done();
}).next(function (done) {
setTimeout(function () {
console.log('World!');
done();
}, 3000);
}).next(function (done) {
setTimeout(function () {
console.log("OK");
done();
}, 2000);
}).end();

Javascript: outside variable used inside closure

I have a simple jquery popup plugin. The usage looks like this:
$("#popupContainer").popup({
onOpen: function () { },
onClose: function () { }
});
$("#popupContainer").popup("open", "/Home/PopupContent");
$("#popupContainer").popup("close");
This works good.
However, i want to pass a different onOpen callback for different url's i have. So i thought about making a wrapper over the plugin, like this:
var popupPlugin = {};
(function () {
var onOpen = null;
var onClose = null;
$("#popupContainer").popup({
onOpen: function () {
if (onOpen) {
onOpen();
}
onOpen = null;
},
onClose: function () {
if (onClose) {
onClose();
}
onClose = null;
}
});
popupPlugin.open = function (url, callback) {
onOpen = callback;
$("#popupContainer").popup("open", url);
}
popupPlugin.close = function (callback) {
onClose = callback;
$("#popupContainer").popup("close");
}
}());
// usage
popupPlugin.open("/Home/PopupContent", function () {
// specific callback
});
This works as expected (i now have different callbacks), but i am worried that i am creating memory leaks somehow.
Is the implementation of the popupPlugin wrapper good?

Categories

Resources