JavaScript/jQuery callbacks of functions - javascript

I have 2 functions.
function f1() {
$.ajax(..., success: function(response) {
// some code executed whenever request is completed.
}
}
function f2() {
// my code
}
I need to call these functions one after another.
f1() // waiting until ajax request in the function is complete.
f2()
I tried $.when().then(), however it didn't seem to work.

The $.ajax call returns an instance of $.Deferred which is used to track the progress of the call - that is what you need to return from your f1 function. You can then use .then(), .done() etc.
Edit in response to comments
If you want to invoke a callback within f1 as well as externally you can return the result of the .pipe method.
function f1() {
return $.ajax(/*...*/).pipe(function() {
//local 'done' handler
});
}
function f2(resultFromF1Handler) {
//...
}
f1().done(f2);

function f1(onsuccess)
{
$.ajax(
{
success: function(r)
{
// some code
onsuccess(r);
}
});
}
function f2()
{
// my code
}
f1(f2);

I suggest calling f2() inside the anonymous function that is executed as f1()'s success.
Is there a problem with doing that?

Related

Cleaner callbacks in JavaScript

If I want to break a callback implementation out of a method's parameter footprint for cleaner code I can do (for example)
foo.bar(a, callback(), b);
function callback() {
stuff;
}
instead of
foo.bar(a, function() {
stuff;
}, b);
But what do I do if the method passes something into the callback like three.js's loader functions? (http://threejs.org/docs/#Reference/Loaders/OBJMTLLoader)
foo.bar(callback(object));
function callback(object) {
object.stuff();
}
doesn't seem to work.
Got it. The format should be:
foo.bar(callback);
function callback(object) {
object.stuff();
}
The 2 snippets you've posted are actually different - when you pass an anonymous function as an argument it isn't run immediately, but in the "foo.bar" function itself. However, when you pass it as "callback()", that function runs immediately (it is useful in some cases, for example: if the function returns another function). So, pass it without "()".
For example:
function a(){
alert(1);
}
function b(callback){
callback(); //run the callback function.
}
b(a);
And, if you want to see an example of the second option:
function a(){
return function() {
alert(1);
};
}
a()(); //Alert
b(a()); //Alert
b(a) //nothing happens

Make a function that can perform multiple callback with one parameter

I'm working on a big project and I simplified what it matters here. This is the code:
a = new Thing(/*sayHi + sayHey*/);
function sayHi() {
alert("hi");
}
function sayHey() {
alert("hey");
}
function Thing (callback) {
callback();
}
I'd like to, with just the callback parameter, call both the sayHi() and the sayHey() function, at the order I put them. Is it possible? How would I do it? Thank you.
Pass an anonymous function that calls both of them sequentially:
a = new Thing(function() {
sayHi();
sayHey();
});
function sayHi() {
alert("hi");
}
function sayHey() {
alert("hey");
}
function Thing (callback) {
callback();
}
Alternatively to #Barnar's answer, create and pass a regular named function. If the callback logic gets heavier, you might want that anyway.
function hiHeyCallback() {
sayHi();
sayHey();
}
a = new Thing(hiHeyCallback);

Callback after $.get?

I have a javascript function foo. I want bar to be called when foo is complete. I have tried it as a callback. It does not work. Bar is called while foo is still executing the $.get (which starts a very long python routine on the server).
function foo(callback){
$.get(
url="/myurl",
data={key:($(this).attr('data-button'))},
function(returndata) {
var array = eval(returndata);
drawTable(array);
});
callback();
}
foo(bar);
This however works. I am confused as to why...
function foo(callback){
$.get(
url="/myurl",
data={key:($(this).attr('data-button'))},
function(returndata) {
var array = eval(returndata);
drawTable(array);
callback();
});
}
foo(bar);
this is because $.get is asynchronous.
from the docs ...
This is a shorthand Ajax function, which is equivalent to:
$.ajax({
url: url,
data: data,
success: success,
dataType: dataType
});
you can think of it being run in a separate thread. so bar() wont act as a callback . but in your 2nd example "function(returndata)" is the callback function for $.get hence giving bar() inside will do the job as now bar() will only be called after $.get is finished.
it's working in second case as 'bar()' is being called once the response comes .Now coming back to callback, Simple concept of writing callback is below :
function func1(callback) {
alert('func1');
callback();
}
function func2() {
alert('func2');
}
func1(func2);
so in your case, ideally this should work :
function foo(callback) {
$.get(
url = "/myurl",
data = {
key: ($(this).attr('data-button'))
},
function(returndata) {
var array = eval(returndata);
drawTable(array);
callback.call();
});
}
function bar() {
//todo
}
foo(bar);

Listen for a function to be called JavaScript

I have the following functions that is called every 2 seconds to load some data. It registers the function [do] to do the stuff with the response. (the example is simplified).
function doRequest (){
$.ajax({ url: 'www.google.com.pe', success: function (response) {do(response)} });
}
function do (text){
var i = setInterval(doRequest, 2000);
}
I wonder if there is any way that I can create a function that is called every time the [do] function is called with out needing to add a call to the listener inside the do function. If there is any better way to do it with jQuery, like a plugin I'd appreciate the help.
[Edit] The idea is not whether it works or not. My question was about if I can add a custom listener to the "do" function which was already implemented. Something like addActionListener("do", "after", doSomeThingElse),sSo I could do some thing else just after the do function has finished.
First, your simplified version won't work, because you'd need to pass the do function instead of calling it.
function doRequest (){
$.ajax({ url: 'www.google.com.pe', success: _do });
}
But it sounds like you're asking how to run some other code every time do is invoked.
If do is only invoked inside the doRequest() function, then just add your other code to an anonymous function that invokes do at the right time.
function doRequest (){
$.ajax({ url: 'www.google.com.pe', success: function(response) {
// Run your other code
// or invoke another function.
_do(response);
} });
}
If you want it to be more generalized, you can create a function decorator that returns a function which invokes do after some other code.
function doFactory(fn) {
return function() {
fn.apply(this, arguments);
_do.apply(this, arguments);
}
}
then make functions like this:
var doFoo = doFactory(function() {
console.log("foo");
});
If your requirement is more specific of a pre-processing of response, you could rework it like this:
function doFactory(fn) {
return function(response) {
_do.call(this, fn.call(this, response));
}
}
Then have the fn manipulate and return response.
var doFoo = doFactory(function(response) {
return response + "foo";
});
If you want to keep existing code as it is, you could wrap do() in another function which in turn calls do() and your new function (say do_this_as_well()).
See the example below (I renamed do() to do_this() to avoid confusion around the reserved keyword do). This works because global functions are nothing but variables with function objects in them. These variables can be overwritten, in this case with a new function that calls the old one:
function do_this(response) { ... }
(function()
{
var previous=do_this;
do_this=function(response) { previous(response); do_this_as_well(); }
})();
Replace
success: do(response)
with
success: function(response) { do(response); do_this_as_well(); }

Call a function after previous function is complete

I have the following JavaScript code:
$('a.button').click(function(){
if (condition == 'true'){
function1(someVariable);
function2(someOtherVariable);
}
else {
doThis(someVariable);
}
});
How can I ensure that function2 is called only after function1 has completed?
Specify an anonymous callback, and make function1 accept it:
$('a.button').click(function(){
if (condition == 'true'){
function1(someVariable, function() {
function2(someOtherVariable);
});
}
else {
doThis(someVariable);
}
});
function function1(param, callback) {
...do stuff
callback();
}
If you're using jQuery 1.5 you can use the new Deferreds pattern:
$('a.button').click(function(){
if(condition == 'true'){
$.when(function1()).then(function2());
}
else {
doThis(someVariable);
}
});
Edit: Updated blog link:
Rebecca Murphy had a great write-up on this here: http://rmurphey.com/blog/2010/12/25/deferreds-coming-to-jquery/
Try this :
function method1(){
// some code
}
function method2(){
// some code
}
$.ajax({
url:method1(),
success:function(){
method2();
}
})
This answer uses promises, a JavaScript feature of the ECMAScript 6 standard. If your target platform does not support promises, polyfill it with PromiseJs.
Promises are a new (and a lot better) way to handle asynchronous operations in JavaScript:
$('a.button').click(function(){
if (condition == 'true'){
function1(someVariable).then(function() {
//this function is executed after function1
function2(someOtherVariable);
});
}
else {
doThis(someVariable);
}
});
function function1(param, callback) {
return new Promise(function (fulfill, reject){
//do stuff
fulfill(result); //if the action succeeded
reject(error); //if the action did not succeed
});
}
This may seem like a significant overhead for this simple example, but for more complex code it is far better than using callbacks. You can easily chain multiple asynchronous calls using multiple then statements:
function1(someVariable).then(function() {
function2(someOtherVariable);
}).then(function() {
function3();
});
You can also wrap jQuery deferrds easily (which are returned from $.ajax calls):
Promise.resolve($.ajax(...params...)).then(function(result) {
//whatever you want to do after the request
});
As #charlietfl noted, the jqXHR object returned by $.ajax() implements the Promise interface. So it is not actually necessary to wrap it in a Promise, it can be used directly:
$.ajax(...params...).then(function(result) {
//whatever you want to do after the request
});
Or you can trigger a custom event when one function completes, then bind it to the document:
function a() {
// first function code here
$(document).trigger('function_a_complete');
}
function b() {
// second function code here
}
$(document).bind('function_a_complete', b);
Using this method, function 'b' can only execute AFTER function 'a', as the trigger only exists when function a is finished executing.
you can do it like this
$.when(funtion1()).then(function(){
funtion2();
})
This depends on what function1 is doing.
If function1 is doing some simple synchrounous javascript, like updating a div value or something, then function2 will fire after function1 has completed.
If function1 is making an asynchronous call, such as an AJAX call, you will need to create a "callback" method (most ajax API's have a callback function parameter). Then call function2 in the callback. eg:
function1()
{
new AjaxCall(ajaxOptions, MyCallback);
}
function MyCallback(result)
{
function2(result);
}
If method 1 has to be executed after method 2, 3, 4. The following code snippet can be the solution for this using Deferred object in JavaScript.
function method1(){
var dfd = new $.Deferred();
setTimeout(function(){
console.log("Inside Method - 1");
method2(dfd);
}, 5000);
return dfd.promise();
}
function method2(dfd){
setTimeout(function(){
console.log("Inside Method - 2");
method3(dfd);
}, 3000);
}
function method3(dfd){
setTimeout(function(){
console.log("Inside Method - 3");
dfd.resolve();
}, 3000);
}
function method4(){
console.log("Inside Method - 4");
}
var call = method1();
$.when(call).then(function(cb){
method4();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
If function1 is some sync function that you want to turn into an async one because it takes some time to complete, and you have no control over it to add a callback :
function function1 (someVariable) {
var date = Date.now ();
while (Date.now () - date < 2000); // function1 takes some time to complete
console.log (someVariable);
}
function function2 (someVariable) {
console.log (someVariable);
}
function onClick () {
window.setTimeout (() => { function1 ("This is function1"); }, 0);
window.setTimeout (() => { function2 ("This is function2"); }, 0);
console.log ("Click handled"); // To show that the function will return before both functions are executed
}
onClick ();
The output will be :
Click handled
...and after 2 seconds :
This is function 1
This is function 2
This works because calling window.setTimeout () will add a task to the JS runtine task loop, which is what an async call makes, and because the basic principle of "run-to-completion" of the JS runtime ensures that onClick () is never interrupted before it ends.
Notice that this as funny as it makes the code difficult to understand...

Categories