简体   繁体   中英

chaining ajax functions - where to place async await

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`
}

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
    });
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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