简体   繁体   English

上一个完成后发起一个function

[英]initiate a function after the previous one is completed

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.当我加载页面时,第一个页面执行,但我认为它在其他 2 个完成后完成,因为它加载了更多内容(需要更多时间),所以就像最后两个没有执行,因为它们使用之前的 function 的元素工作。

How can I make the second one (AtualizarComentarios) initiate after the first (AtualizarPublicacoes) is completed and the third one after the second?如何在第一个 (AtualizarPublicacoes) 完成后启动第二个 (AtualizarCommentarios) 并在第二个之后启动第三个?

I call them on other events as well so I can't put them all togheter in one function.我也会在其他活动上打电话给他们,所以我不能把它们都放在一个 function 中。

Thanks!谢谢!

jQuery ajax methods return promise compatible objects, so you could use that. jQuery ajax 方法返回 promise 兼容对象,因此您可以使用它。 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 更改为以下内容 - 关键是使用then而不是success返回then调用的结果:

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:在调用代码中,要么链then调用,要么(更简单)使用async / await语法:

$(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'
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM