Reputation: 614
I'm trying to use a promise to make sure a certain function doesn't fire until another function has returned. I've looked at a lot of examples, others' problems etc., and as far as I can tell my syntax is correct, but my .then(function())
won't run, so I must be missing something.
function previewMaster () {
var dfd = $.Deferred();
function prevAndTest() {
return true;
}
var doneYet = false;
var intvl = setInterval(function() {
if (doneYet === false) {
doneYet = prevAndTest();
//reassign doneYet until true
} else {
clearInterval(intvl);
dfd.resolve;
return dfd.promise();
}
}, 1000);
}
neither .then()
nor .done()
work here:
var promise = previewMaster();
promise.then(function() {
alert("finished");
});
Upvotes: 0
Views: 880
Reputation: 3440
You solution does not work because the method previewMaster
is not returning the promise:
function previewMaster () {
...
return dfd.promise();
}
and because you need to call the resolve
function when you want to resolve the promise:
dfd.resolve();
See the complete example here:
function previewMaster () {
var dfd = $.Deferred();
function prevAndTest() {
return true;
}
var doneYet = false;
var intvl = setInterval(function() {
if (doneYet === false) {
doneYet = prevAndTest();
//reassign doneYet until true
} else {
clearInterval(intvl);
dfd.resolve(); // <- resolve method must be called to resolve the promise.
// return dfd.promise(); // <- Do not return the promise here
}
}, 1000);
return dfd.promise(); // <- Return the promise here
}
Upvotes: 2