Nested Execution Flow Control
Posted
by
chris
on Stack Overflow
See other posts from Stack Overflow
or by chris
Published on 2014-05-29T04:13:57Z
Indexed on
2014/05/29
15:27 UTC
Read the original article
Hit count: 238
I've read tens of answers related to callbacks, promises and other ways to control flow, but I can't still wrap my head around this task, obviously due to my lack of competence.
I have a nested problem:
- In
test_1()
(and the other functions) I would like to ensure that the rows are added to the table according to the order in which the elements are in the object; - I would like to execute either test_2 or test_3 (or both after each other) only after test_1 has finished completely. Actually the right sequence will only be known at runtime (there will be a switch with the possible sequences, like 1,2,3 or 1,3,2 or 1,2,1,3 or 1,3,3,2, etc...)
Code:
$(function () {
// create table
tbl = document.createElement('table');
tbl.className = "mainTbl";
$("body").append(tbl);
});
function test_1() {
$.each(obj, function () {
var img = new Image();
img.onload = function () {
// add row of data to table
var row = tbl.insertRow(-1);
var c1 = row.insertCell(0);
c1.innerHTML = "loaded";
};
img.onerror = function () {
// add row of data to table
var row = tbl.insertRow(-1);
var c1 = row.insertCell(0);
c1.innerHTML = "not loaded";
};
img.src = this.url;
});
}
function test_2() {
$.each(obj, function () {
var img = new Image();
img.onload = function () {
// add row of data to table
var row = tbl.insertRow(-1);
var c1 = row.insertCell(0);
c1.innerHTML = "loaded";
};
img.onerror = function () {
// add row of data to table
var row = tbl.insertRow(-1);
var c1 = row.insertCell(0);
c1.innerHTML = "not loaded";
};
img.src = this.url;
});
}
function test_3() {
$.each(obj, function () {
var img = new Image();
img.onload = function () {
// add row of data to table
var row = tbl.insertRow(-1);
var c1 = row.insertCell(0);
c1.innerHTML = "loaded";
};
img.onerror = function () {
// add row of data to table
var row = tbl.insertRow(-1);
var c1 = row.insertCell(0);
c1.innerHTML = "not loaded";
};
img.src = this.url;
});
}
I know that calling the functions in sequence doesn't work as they don't wait for each other... I think promises are they way to go but I can't find the right combination and the documentation is way too complex for my skills.
What's the best way to structure the code so that it's executed in the right order?
© Stack Overflow or respective owner