简体   繁体   中英

Javascript - Setting global variables

I'm running into an issue with setting the value of global variables. When my function GetUserList() is called, it returns an array of globalUsers when it is run inside the function.

However, when I log the console again after running the function, the array being returned is empty. I feel there must be something wrong with the logic, or the manner in which the code is being executed.

I'm seeking that the value of globalUsers is set within the function for future use throughout the rest of the script.

Your assistance would be greatly appreciated. See the code below:

var globalUsers = [];

function GetUserList(){
    var userList = $().SPServices.SPGetListItemsJson({
                listName: "Users",
                CAMLQuery: "<Query><OrderBy><FieldRef Name='ID' /></OrderBy></Query>",
                async: false,

                mappingOverrides: {
                    ows_Title: {
                        mappedName: "Name",
                        objectType: "Text"
                    },
                    ows_ID: {
                        mappedName: "id",
                        objectType: "Text"
                    },
                    ows_Group: {
                        mappedName: "Group",
                        objectType: "Text"
                    }
                }
            });

            $.when(userList).done(function() {
                thisUserList = this.data;
                globalUsers = thisUserList;
                console.log(globalUsers);
            });
}


    $(document).ready(function () {
        GetUserList();
        console.log(globalUsers);
    }
    );

It's because you're not waiting until the globalUsers variable has been updated.

In the GetUserList function, you're explicitly waiting for the assignment assignment to complete before logging out the result, whereas the console.log in your $(document).ready block is executing the log immediately (as GetUserList is non-blocking).

Try logging out the value in dev tools, I bet you'll see what you're expecting (assuming the async assignment has taken place).

Alternatively, you could use a promise to ensure that you're only attempting assignment once the getUserList method has completed:

function GetUserList () {
  return new Promise((resolve, reject) => {
    var userList = $().SPServices.SPGetListItemsJson({
      listName: "Users",
      CAMLQuery: "<Query><OrderBy><FieldRef Name='ID' /></OrderBy></Query>",
      async: false,

      mappingOverrides: {
          ows_Title: {
              mappedName: "Name",
              objectType: "Text"
          },
          ows_ID: {
              mappedName: "id",
              objectType: "Text"
          },
          ows_Group: {
              mappedName: "Group",
              objectType: "Text"
          }
      }
    });

    // Should also handle errors in here somewhere, and reject if they occur...

    $.when(userList).done(function() {
      resolve(this.data);
      console.log('Logging from within getUserList: ', globalUsers);
    });
  })
}


$(document).ready(function () {
  GetUserList().then((userList) => {
    console.log(userList);
    globalUsers = userList; // Global assignment
  })
});

Also, cursory don't use global variables, mmmKay?

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