I've written a little program to help me understand how to do nested asynchronous promises in jquery.
I want to call two tasks, in sequence. The first task has two subtasks that also are called in sequence. That's all.
While this works, I have doubts as to whether this was the best way to use promises. Having to create a new deferred for every task feels like code smell to me. For example, would it be better to pass a single deferred object around and use only that? Thanks!
https://plnkr.co/edit/dyFFqqZhCVuhBYCuWjzm?p=preview
doTasks().then(function(arg) {
console.log(arg)
})
function doTasks() {
var d = $.Deferred();
task1().then(function(arg) {
console.log(arg)
task2().then(function(arg) {
console.log(arg)
d.resolve('all tasks are done')
})
})
return d.promise();
}
function task1() {
var d = $.Deferred();
console.log("starting task1...")
setTimeout(function() {
task1A().then(function() {
task1B().then(function() {
d.resolve('task1 is done')
})
})
}, 10);
return d.promise();
}
function task1A() {
var d = $.Deferred();
console.log("starting task1A...")
setTimeout(function() {
console.log(" resolving task1A...")
d.resolve();
}, 1000);
return d.promise();
}
function task1B() {
var d = $.Deferred();
console.log("starting task1B...")
setTimeout(function() {
console.log(" resolving task1B...")
d.resolve();
}, 1000);
return d.promise();
}
function task2() {
var d = $.Deferred();
console.log("starting task2...")
setTimeout(function() {
d.resolve('task2 is done');
}, 1000);
return d.promise()
}