.done function is not working with defer and promises - javascript

Things that I have tried: -
var dfd = $.Deferred();
$("#Index").click(function(){
dfd.resolve();
}).done(function(){
CallNextFunction();
})
I created a deferred object and when click is done, I want next function to be called but it never does.
Second Try
function CompletePage(){
var dfd = $.Deferred();
$("#Index").click(function(){
dfd.resolve();
});
return dfd.promise();
}
CompletePage().done(function(){
// Call Next Function();
});
This also does not work.

Related

jquery $.done is executed immedietely

$.when(fetchingOutcomeTab()).done(alert("1"));
function fetchingOutcomeTab() {
var dfd = $.Deferred();
setTimeout(function() {
dfd.resolve('qqqqq');
}, 2000);
return dfd.promise();
}
I am trying to make alert("1") triggered waiting until fetchingOutcomeTab function done, but everytime it will triggered immedietely, please help.
You need to pass a function to .done(). You're calling alert() immediately and passing its return value.
$.when(fetchingOutcomeTab()).done(() => alert("1"));
Since your function returns a deferred object, you can chain done() directly to the function call. Also, done() expects a parameter that's a "function or array of functions".
fetchingOutcomeTab().done(function() {
console.log('resolved.');
});
function fetchingOutcomeTab() {
console.log('Deferring...');
var dfd = $.Deferred();
setTimeout(function() {
dfd.resolve('qqqqq');
}, 2000);
return dfd;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

jQuery deffered resolve multiple times

jQuery:
var dfd = $.Deferred();
$(document).on('click', '#Signup', function() {
email_check('Signup');
mobile_check('Signup');
dfd.done(function(){
alert("Hello World!")
})
})
function email_check(Signup){
dfd.resolve();
}
function mobile_check(Signup){
dfd.resolve();
}
Hi everyone, I want that when deferred object resolve in both function email_check and mobile_check. Then after executing the alert statement. How can I do this please help me.
Use $.when() to wait for the promises (deferreds) to be resolved
Provides a way to execute callback functions based on zero or more Thenable objects, usually Deferred objects that represent asynchronous events.
$(document).on('click', '#Signup', function() {
console.log("Signup...");
$.when(email_check('Signup'), mobile_check('Signup'))
.done(function(){
console.log("All done!")
});
});
function email_check(Signup){
var d = $.Deferred();
setTimeout(function() {
console.log("email_check resolved");
d.resolve();
}, 1000);
return d;
}
function mobile_check(Signup){
var d = $.Deferred();
setTimeout(function() {
console.log("mobile_check resolved");
d.resolve();
}, 2000);
return d;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="Signup">Signup</button>

Jquery Deferred Not reaching last .then

I have a sequence of functions that must be executed. They all execute sequentially except the last one. d1 executes, d2 executes, d3 executes then the code inside the done function executes before the resolve of d4. Can't figure out why. Any help would be appreciated.
$(document).ready(function() {
var d1 = functiond1();
var d2 = functiond2();
var d3 = functiond3();
var d4 = functiond4();
d1.then(d2).then(d3).then(d4).done(function() {
//Code here does not wait for d4 to end before executing
//HELP!
});
});
function functiond1() {
var dfd = $.Deferred();
//Do stuff here
//Works in sequence
dfd.resolve();
return dfd.promise();
}
function functiond2() {
var dfd = $.Deferred();
params = jQuery.param({
'parm1': 1,
'parm2': 2,
'parm3': 3
});
jQuery.getJSON($.webMethoJSONGet1, params).done(function(data) {
//Do stuff here
//Works in sequence
dfd.resolve();
});
return dfd.promise();
}
function functiond3() {
var dfd = $.Deferred();
//Do stuff here
//Works in sequence
dfd.resolve();
return dfd.promise();
}
function functiond4() {
var dfd = $.Deferred();
params = jQuery.param({
'parm1': 1,
'parm2': 2,
'parm3': 3
});
jQuery.getJSON($.webMethoJSONGet2, params).done(function(data) {
//Do stuff here
//does not work in sequence
dfd.resolve();
});
return dfd.promise();
}
It's hard to tell what you are trying to do with those promises. You first call all 4 functions, and then you try to chain them with a bunch of then callbacks. If you want to sequentially chain them together it should look like this:
functiond1()
.then(functiond2)
.then(functiond3)
.then(functiond4)
.done(function() { /* blah */ });
If you just want a result after all have completed you can use $.when
$.when(functiond1(), functiond2(), functiond3(), functiond4())
.then(function(resultd1, resultd2, resultd3, resultd4) { /* blah */ });
On another note, in your functions you create promises that are resolved inside the done callback of another promise which is unnecessary. The $.getJSON.done() calls return a promise themselves so an additional promise is not needed. Just return the promise returned from done().
Sorry, I haven't messed much with jQuery deferred objects, but they appear similiar enough to standard Promises.
To run the functions in sequence, you need to pass references to the functions within the .then chain, and not the results of calling those functions.
e.g.
var d1 = functiond1; // NB: no ()
...
d1.then(d2).then(d3).then(d4).done(...);
functiond1().then(functiond2).then(functiond3).then(functiond4).done(...)
The ultimate cause of your problem is that invoking d4 straight away will cause its resolved promise to pass-thru to .done immediately irrespective of the state of the earlier part of the .then chain.
You should also not wrap your JSON functions with additional promises, since $.getJSON already returns a promise that will be rejected if the AJAX query fails:
function functiond4() {
...
return $.getJSON(...);
}
I was facing the same issue on a project, this solution with an array works well:
$(document).ready(function() {
var pr = [];
var d1 = functiond1();
var d2 = functiond2();
var d3 = functiond3();
var d4 = functiond4();
function functiond1() {
var dfd = $.Deferred();
pr.push(dfd);
setTimeout(function(){
$('body').append('1 resolved <br>');
dfd.resolve();
}, 2000);
}
function functiond2() {
var dfd = $.Deferred();
pr.push(dfd);
params = jQuery.param({
'parm1': 1,
'parm2': 2,
'parm3': 3
});
setTimeout(function(){
$('body').append('2 resolved <br>');
dfd.resolve();
}, 3000);
}
function functiond3() {
var dfd = $.Deferred();
pr.push(dfd);
setTimeout(function(){
$('body').append('3 resolved <br>');
dfd.resolve();
}, 1000);
}
function functiond4() {
var dfd = $.Deferred();
pr.push(dfd);
params = jQuery.param({
'parm1': 1,
'parm2': 2,
'parm3': 3
});
setTimeout(function(){
$('body').append('4 resolved <br>');
dfd.resolve();
}, 50);
}
$.when.apply($, pr).then(function() {
// do something
$('body').append('proceed with code execution');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Run function after 1sec from loading [duplicate]

I want to have one callback function after actions are done, I'm trying something like this:
$.when(
$('#detail1').load('/getInfo.php'),
$('#detail2').load('/getOther.php')
).then(function(a,b){
alert("done");
});
The problem is that the callback function is firing before the actions are finished.
This is because jQuery.when() expects jQuery.Deferred instances while load() returns an jQuery instance (see http://api.jquery.com/jQuery.when/ and http://api.jquery.com/load/).
You can work around this issue:
// Create two Deferred instances that can be handed to $.when()
var d1 = new $.Deferred();
var d2 = new $.Deferred();
// Set up the chain of events...
$.when(d1, d2).then(function() {
alert('done');
});
// And finally: Make the actual ajax calls:
$('#detail1').load('/getInfo.php', function() { d1.resolve(); });
$('#detail2').load('/getOther.php', function() { d2.resolve(); });
I do a similar code but for images in a more dynamic way. Hope that it help.
var deferreds = [];
// Create a deferred for all images
$('.my-img-class').each(function() {
deferreds.push(new $.Deferred());
});
var i = 0;
// When image is loaded, resolve the next deferred
$('.my-img-class').load(function() {
deferreds[i].resolve();
i++;
});
// When all deferreds are done (all images loaded) do some stuff
$.when.apply(null, deferreds).done(function() {
// Do some stuff
});

jQuery deferred and promise not work corectly

I have this code:
var d = $.Deferred();
var promise = d.promise();
//
promise = promise.then(function(){
var t = new $.Deferred();
var cont = $('.cont').find('> div');
requirejs(["transit"], function(){
cont.transit({opacity: .4});
//
setTimeout(function(){
cont.remove();
return t.promise();
}, 500);
});
});
//
promise.then(function() {
console.log('test');
});
//
d.resolve();
I wanna to fire up some action after another. But i need to be shure that the first one is finished. So i use promise and deferred methods. Something is not right bc second action starts before defined timeout delay. What is wrong? Can anybody help?
chain does not correctly setup?
The t promise has not been returned to the chain of d.
Modified code
var d = $.Deferred();
var promise = d.promise();
//
promise = promise.then(function(){
var t = new $.Deferred();
console.log('1st promise callback');
//var cont = $('.cont').find('> div');
setTimeout(function(){
//requirejs(["transit"], function(){
//cont.transit({opacity: .4});
//
console.log('timeout 1 func');
setTimeout(function(){
console.log('timeout 2 func');
//cont.remove();
t.resolve(true);
}, 10);
},30);
return t.promise();
});
//
promise.then(function() {
console.log('test');
});
//
d.resolve();
Output
1st promise callback (index):27
timeout 1 func (index):33
timeout 2 func (index):36
test
fiddle here
Why not use the $.when
$.when(function).done(function( x ) {
console.log('test');
});
You are using some Kind of non-Jquery, asynchronous (which is completely unnecessary if you already have jQuery) function- as asynchronous operations run on a separate thread the caller will finish nigh-instantly. If you really want to ensure sequential execution you may simply use a proper jQuery UI method (like animate : http://api.jquery.com/animate/) and add a complete-handler, as documented in the link

Categories