Reputation: 114
I have three functions:
function atualizarPublicacoes(){
$.ajax({
url: "{{ path('publicacoes') }}",
type: 'post',
dataType: 'json',
success: function(publicacao){
$.each(publicacao, function(key, value){
$('#mural').append('<div class="border border-light post card my-3"><div id="cabecalho'+value['id']+'" class="px-4 card-header d-flex align-items-center justify-content-between"><div class="d-flex align-items-center"><img class="rounded-circle avatar" style="height:55px ; width:55px" alt="image" src="'+value['userAvatar']+'"></img><div class="mx-3"><div class="text-sm">'+value['userNomeSobrenome']+'<small class="text-muted d-block">'+moment(value['data']).fromNow()+'</small></div></div></div></div><div class="card-body">'+value['post']+'</div><div class="card-footer px-4" style="background-color: #B7BBE0"><div id="acoes'+value['id']+'"></div><div></div></div><div class="card-footer" style="background-color: #CACDE7"><ul class="list-unstyled" id="comentarios'+value['id']+'"></ul></div>');
if(value['titulo']){
$('#cabecalho'+value['id']).append('<h3 class="mb-0" style="font-family: Nunito Sans, sans-serif">'+value['titulo']+'</h3>');
}
if(value['userId'] == "{{app.user.id}}"){
$('#cabecalho'+value['id']).append('<div><button id="editar'+value['id']+'" class="btn btn-gradient-info btn-sm" data-toggle="tooltip" data-placement="top" title="Editar"><i class="mdi mdi-lead-pencil"></i></button><button id="deletar'+value['id']+'" class="ml-2 btn btn-gradient-danger btn-sm" data-toggle="tooltip" data-placement="top" title="Excluir"><i class="mdi mdi-delete-forever"></i></button></div>');
}
});
}
});
};
function atualizarCurtidas(id){
$.ajax({
url: "{{ path('publicacoes_footer')}}",
type: 'post',
datatype: 'json',
success: function(footer){
if(!id){
var footers = footer; //atualiza todos os footers - utilizado quando abre a pagina ou publica um novo post
}else{
var footers = [footer.find(e => e.id == id)]; //atualiza só o footer clicado
}
$.each(footers, function(key, value){
var acoes = $('#acoes'+value['id']);
if( value['curtidas'] != null && "{{ app.user.id }}" in value['curtidas']){
acoes.find('a[title="Comentarios').before('<a title="Curtido" class="ml-2 mr-1" style="cursor:pointer"><i class="icon-md mdi mdi mdi-heart" style="color: #FF4747"></i><small class="mx-1" style="color: #FF4747">'+value['countCurtidas']+'</small></a>');
}else{
acoes.find('a[title="Comentarios').before('{{ form_start(curtir) }}{{ form_widget(curtir._token) }}{{ form_end(curtir, {"render_rest": false}) }}<a title="Curtir" id="'+value['id']+'" class="ml-2 mr-1" style="cursor:pointer"><i class="icon-md mdi mdi mdi-heart-outline" style="color: #FF4747"></i><small class="mx-1" style="color: #FF4747">'+value['countCurtidas']+'</small></a>');
}
});
}
});
};
function atualizarComentarios(id){
$.ajax({
url: "{{ path('publicacoes_footer')}}",
type: 'post',
datatype: 'json',
success: function(footer){
if(!id){
var footers = footer; //atualiza todos os footers - utilizado quando abre a pagina ou publica um novo post
}else{
var footers = [footer.find(e => e.id == id)]; //atualiza só o footer clicado
$('#acoes'+footers[0]['id']).parent().next().find('ul').empty();
}
$.each(footers, function(key, value){
if(value['countComentarios'] > 0){
$('#acoes'+value['id']).append('<a title="Comentarios" class="ml-2 mr-1"><i class="icon-md mdi mdi-comment-processing text-primary"></i><small class="mx-1 text-primary">'+value['countComentarios']+'</small></a>');
$(value['comentarios']).each(function(key, comm){
$('#comentarios'+value['id']).append('<li class="p-2 media rounded mb-2" style="background-color: #E5E6EA ; box-shadow: 0 0 6px gray"><img class="align-self-center mx-2 rounded-circle avatar" style="height:45px ; width:45px" alt="image" src="'+comm['userAvatar']+'"></img><div class="media-body"><h6 class="m-0 text-info">'+comm['userNome']+'<small class="text-muted float-right">'+moment(comm['data']).fromNow()+'</small></h6><small class="mx-2">'+comm['texto']+'</small></div></li>');
$('#comentarios'+value['id']).addClass(value['countComentarios'] > 2 ? '3mais' : '');
})
}else{
$('#acoes'+value['id']).append('<a title="Comentarios" class="ml-2 mr-1"><i class="icon-md mdi mdi-comment-processing-outline text-primary"></i><small class="mx-1 text-primary">0</small></a>');
}
if(!id){
$('#comentarios'+value['id']).after('<div tabindex="-1" class="d-flex justify-content-between align-items-center mx-2 mb-2"><img class="rounded-circle avatar" style="height:45px ; width:45px" alt="avatar" src="{{asset(app.user.avatar)}}"></img><textarea placeholder="'+ (value["countComentarios"] > 0 ?'Escreva seu comentário...' : 'Seja o primeiro a comentar...') +'" class="p-2 mx-1 col-11" maxlength="250"></textarea><a title="Comentar" data-pub="'+value['id']+'" style="cursor:pointer">{{ form_start(comentar) }}{{ form_widget(comentar._token) }}{{ form_end(comentar, {"render_rest": false}) }}<i class="icon-lg mdi mdi-comment-check text-primary"></i></a></div>');
}
});
if(!id){
$('ul.list-unstyled li:nth-child(n+3)').hide();
$('ul.3mais li:nth-last-child(1)').after('<a name="carregar" class="ml-3 text-info" style="cursor:pointer">Carregar mais comentários<i class="mdi mdi-menu-down"></i></a>');
}
}
});
};
and then i call them:
$(document).ready(function(){
moment.locale('pt-BR');
atualizarPublicacoes();
atualizarComentarios();
atualizarCurtidas();
Notiflix.Notify.Init({
position: 'center-top'
});
Notiflix.Confirm.Init({
titleColor: '#ff5549',
okButtonBackground: '#ff5549'
});
});
When I load the page the first one executes but I think that it's finishing after the other 2 finishes because it loads more content (takes more time) so it's like the last two ones didn't executed as they use elements of the previous function to work.
How can I make the second one (AtualizarComentarios) initiate after the first (AtualizarPublicacoes) is completed and the third one after the second?
I call them on other events as well so I can't put them all togheter in one function.
Thanks!
Upvotes: 0
Views: 230
Reputation: 349946
jQuery ajax methods return promise compatible objects, so you could use that. For instance, change the first function to the following -- the key is to use then
instead of success
and to return the result of the then
call:
function atualizarPublicacoes(){
return $.ajax({
//^^^^^^
url: "{{ path('publicacoes') }}",
type: 'post',
dataType: 'json'
}).then(function(publicacao){
// ^^^^^^
$.each(publicacao, function(key, value){
// ... etc ...
});
});
};
Do the same with the other two functions.
In the calling code, either chain then
calls, or (simpler) use the async
/await
syntax:
$(document).ready(async function(){
// ^^^^^
moment.locale('pt-BR');
await atualizarPublicacoes();
//^^^^^
await atualizarComentarios();
await atualizarCurtidas();
Notiflix.Notify.Init({
position: 'center-top'
});
Notiflix.Confirm.Init({
titleColor: '#ff5549',
okButtonBackground: '#ff5549'
});
});
Upvotes: 1