Home > Blockchain >  chaining ajax functions - where to place async await
chaining ajax functions - where to place async await

Time:06-07

here is the scenario:

btnplus function - inserts some new data into a database

it calls get_atitles - which is also an ajax call to populate a div with the new set of data

when the div is populated - go_find should find a specific element inside the new set. This is not an ajax

problem - go_find starts before get_atitles is finished so it cannot find the required data

I tried to place async await on various places - without success

so how to call go_find after get_atitles is completed ?

$(btnplus).on('click', function(){
    ...
    $.post('pro.php', {fn: 'btn_plus_fi', args: [path]}, async function(data){
        // some new data is added to database
        await get_atitles(); // load the new set of data into a div
        go_find(str); // find a specific data inside a new set
    });
});

function get_atitles(){
    ...
    $.post('pro.php', {fn: 'get_atitles', args: [par]}, function(data){
        atitles.html(data);
    });
}

function go_find(str){
    // find something inside `atitles`
}

CodePudding user response:

Re: so how to call go_find after get_atitles is completed ?

Just put go_find function call inside the get_atitles result handler.

$(btnplus).on('click', function() {

  $.post('pro.php', {
    fn: 'btn_plus_fi',
    args: [path]
  }, async function(data) {
    // some new data is added to database
    await get_atitles(); // load the new set of data into a div
  });
});

function get_atitles() {

  $.post('pro.php', {
    fn: 'get_atitles',
    args: [par]
  }, function(data) {

    atitles.html(data);

    go_find(str); // find a specific data inside a new set
  });
}

function go_find(str) {
  // find something inside `atitles`
}

Alternative

$(btnplus).on('click', function () {

  $.post('pro.php', { fn: 'btn_plus_fi', args: [path] }, async function (data) {
    // some new data is added to database
    $.post('pro.php', { fn: 'get_atitles', args: [par] }, function (data) {
      atitles.html(data);
      go_find(str); // find a specific data inside a new set
    });
  });
});
  • Related