0

I am trying to create an array of User IDs to send in an AJAX Post Request. I can get the User IDs okay and display them individually in console.log but after I push them to the connectionData array and try to do a console.log on specific indices I get undefined, also when I try console.log(connectionData.length) it returns 0. I believe this is a sync issue but I can't figure out how to solve it, I have read similar posts and they aren't helping.

const prepareUserDataForConnection = function(){

    var connectionData = [];
    var currentUser = 'robert';
    var currentUser = 'chris';
    console.log(currentUser);
    console.log(followedUser);

    $.ajax({
        type: 'GET',
        url: '/api/currentuserinfo/',
        data: {
            'current_user': currentUser
        },
        success: function(data) {
            let currentUserId = JSON.stringify(data[0].id);
            console.log('Current User Pk is: ' + currentUserId);
            connectionData.push(currentUserId);
        }, 
    });
    
    $.ajax({
        type: 'GET',
        url: '/api/followeduserinfo/',
        data: {
            'followed_user': followedUser
        },
        success: function(data) {
            let followedUserId = JSON.stringify(data[0].id);
            console.log('Followed User Pk is: ' + followedUserId);
            connectionData.push(followedUserId);
        },
    }); 
    console.log(connectionData) 
    console.log(connectionData[0]) 
    console.log("Array length is: " + connectionData.length) 
};

Here is a screenshot of the problem: enter image description here

vygrdev
  • 195
  • 1
  • 12
  • All your log commands run before the (async) ajax requests finish, however logging objects is live, so the output gets updated. –  Apr 07 '21 at 11:14
  • 1
    Primarily a dupe of this (#1 JS dupe of all time) [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) –  Apr 07 '21 at 11:14
  • Also of this: https://stackoverflow.com/questions/4057440/is-chromes-javascript-console-lazy-about-evaluating-arrays –  Apr 07 '21 at 11:15
  • Thanks for responding. Yep that's what I learned from other posts, but then I can't access the elements of the array for other purposes it always returns ``undefined`` – vygrdev Apr 07 '21 at 11:15

1 Answers1

0

Try this approach with Promise

function ajaxPromise(obj) {
    return new Promise(function (resolve, reject) {
        obj.success = resolve;
        obj.error = reject;
        $.ajax(obj);
    });
}
const prepareUserDataForConnection = function () {
    var currentUser = 'robert';
    var followedUser = 'chris';

    return Promise.all([
        ajaxPromise({
            type: 'GET',
            url: '/api/currentuserinfo/',
            data: { 'current_user': currentUser }
        }),
        ajaxPromise({
            type: 'GET',
            url: '/api/followeduserinfo/',
            data: { 'followed_user': followedUser }
        })
    ]);
};

prepareUserDataForConnection().then(function (connectionData) {
    console.log(connectionData)
    console.log(connectionData[0])
    console.log("Array length is: " + connectionData.length)
    // Write your logic here with connectionData
}).catch(function (error) {
    console.log(error);
});
Wazeed
  • 1,230
  • 1
  • 8
  • 9