简体   繁体   English

Javascript-设置全局变量

[英]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. 当我的函数GetUserList()被调用时,当它在函数内部运行时,它将返回一个globalUsers数组。

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. 我想在函数内设置globalUsers的值,以备将来在脚本的其余部分中使用。

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. 这是因为您没有等到globalUsers变量被更新。

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). 在GetUserList函数中,您要显式等待分配任务完成,然后注销结果,而$(document).ready块中的console.log将立即执行日志(因为GetUserList是非阻塞的)。

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: 另外,您可以使用promise来确保仅在getUserList方法完成后才尝试分配:

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? 另外,粗略的不要使用全局变量,mmmKay?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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