You'll have to move doSomethingWithResult()
inside of your done()
function, since post()
is async.
function getSomeInfoFromDB(){
let body= "";
let text = "";
$("tr").each(function(){
let code = $(this).children("td:nth-child(2)");
$.post( "http://urltogetdatafromdatabase.com/getinfo.php", { a: code })
.done(function(data) {
text = "<div>"+data+"</div>";
body = body + text;
let bigboody = "<div class='outer'>"+body+"</div>";
doSomethingWithResult(bigboody);
});
});
}
But note that post()
in an each()
, they may return in different orders, which since you're appending them, may not be what you want.
The safer approach (where you can control the order), is to use Promise.all()
and gather the post()
calls up as promises and into an array. Something like this:
function getSomeInfoFromDB(){
let promises = [];
$("tr").each(function(){
let code = $(this).children("td:nth-child(2)");
promises.push(new Promise((resolve) =>
$.post( "http://urltogetdatafromdatabase.com/getinfo.php", { a: code }).done(resolve)
))
});
Promise.all(promises)
.then(datas => '<div>' + datas.join('</div><div>') + '</div>') // easy way to wrap all of them in divs and put them together
.then(body => doSomethingWithResult('<div class="outer">' + body + '</div>');
}
Basically, you wrap each post()
up as a Promise
and put that Promise
in an array. Then, use Promise.all()
which will run when all of the promises are finished. The then()
for that will give you an array of results, one for each post, in order. You can then do whatever you want with them at that point.