Ajax POST request in for loop affecting the POST data during second iteration

I’m sending the ajax request inside for loop, this is how my loop is working:

let postDbData = async ($, ajaxUrl) =>{
  for( let page_num = 1; page_num > 0; page_num++ ){
    let imageData = []; //1. Define an empty Array
    await dbData($, ajaxUrl, page_num).then( i => imageData = i );
     //2. Calls dbData() which returns an array. Assign that that returned array to imageData
    console.log(imageData); 
    await $.post( ajaxUrl, { action: "insert_sync_data_db", imageData: imageData } ) 
     //3. Send imageData to server Using POST request, to save it into database
    if(imageData.length <= 0) page_num = 0; 
     // 4. if dbData() does'nt return an array or return an blank array, set page_num to 0 so we can get out from the loop
  }
}

dbData() returns a unique array in every iteration. What I want to do is, In every iteration replace the imageData array with the new array, But my code is not replacing the previous content instead it’s pushing the new data in imageData .

The Problem occurs in second iteration, The array imageData retains the values of previous iteration ( as if it’s ignoring let imageData = []; ). however, it is not possible.

The array stop retaining the previous values when I comment on my Ajax POST request . after removing post request, my imgData variable’s previous values gets flushed in each iteration and new values appears in imgData ( //await $.post( ajaxUrl, { action: "insert_sync_data_db", imageData: imageData } ) ) I don’t know why this ajax request is messing with my Array.

Here are other Functions on which this function depends.

dbData()

let dbData = async ($, ajaxUrl, page_num) => {

    let data = [];

    await compareImagesToSync($, ajaxUrl, page_num).then( async i => {
        await getImageDetails(i).then( i => {
            i.data.data.forEach( i => {
                let temp = {};
                temp.id = i.id;
                temp.preview_url = i.assets.preview.url;
                temp.description = i.description;
                temp.keywords = i.keywords.join(", ");
                data.push(temp);
            } );
        } );
    } );

    return await data;
}

compareImagesToSync()

let compareImagesToSync = async ($, ajaxUrl, page_num) => {

    let fetchImagesFromDB = async ($, ajaxUrl) => await $.post(ajaxUrl, { action: "get_images_from_db" });

    let fetchImagesFromAPI = async () => await getLicensedImages(page_num, 2);

    let request = async () => await axios.all([fetchImagesFromDB($, ajaxUrl), fetchImagesFromAPI()])
    .then(axios.spread( (db, api) => {
        let dbImages = JSON.parse(db);
        return diffArray(dbImages, api);
    } ))
    .catch(e => console.log(e));

    return await request();
}

getImageDetails()

let getImageDetails = async ( image_id = null ) => {

    if(image_id == null || image_id == "" || image_id.length <= 0) return;

    image_id = image_id.map( v => `id=${v}` ).join('&')

    const APIURL = `https://api.shutterstock.com/v2/images?${image_id}&view=full`;

    const request = async () => await axios.get(APIURL, { headers: auth_header() } );

    return await request();
}

diffArray()

let diffArray = (arr1, arr2) => {

  var newArr = [];

  arr1.map(val => arr2.indexOf(val) < 0 ? newArr.push(val) : '');

  arr2.map(val => arr1.indexOf(val) < 0 ? newArr.push(val) : '');

  return newArr;

}

And Here the PHP function that is Handling the Ajax Request. This might be irrelevant to my question but still, I’m adding this for the better understanding of my code:

add_action( 'wp_ajax_insert_sync_data_db', 'create_shutterstock_image_post' );
add_action( 'wp_ajax_nopriv_insert_sync_data_db', 'create_shutterstock_image_post' );
function create_shutterstock_image_post(){

    ini_set('max_execution_time', 600);
    foreach ($_POST["imageData"] as $value) {
        $postarr = array(
            "post_content" => $value['keywords'],
            "post_title" => $value['description'],
            "post_excerpt" => $value['description'],
            "post_status" => "publish",
            "post_type" => "portfolio",
            "guid" => $value['id'],
            "post_name" => $value['id'],
            "meta_input" => array(
                '_bk_portfolio_thumbnail_behavior' => 'content_link', 
                '_bk_page_builder_item_size_combobox' => 'one_one',
                '_bk_page_builder_items_combobox' => 'bk_accordion',
                '_bk_page_layout' => 'fixed_centered',
                '_bk_fixed_page_width' => '1024',
                '_bk_page_fullscreen_background_content', 'bk-none'
            )
        );
        $postID = wp_insert_post($postarr, true);

        Generate_Featured_Image($value['preview_url'], $postID);
    }
    wp_die();
}