简体   繁体   English

访问从异步函数更新的全局变量

[英]Accessing a global variable that is been updated from an asynchronous function

i'm really struggling to understand the asynchronous side of JavaScript. 我真的很难理解JavaScript的异步方面。 the code i have is meant to collate specific details of certain users and then put all the collated information into a global variable array which i intent to manipulate when all the users have been added to the array. 我拥有的代码旨在整理某些用户的特定详细信息,然后将所有整理的信息放入一个全局变量数组中,当所有用户都添加到该数组时,我打算进行操作。 i'm finding it difficult to iterate the array because when i do an array.length on the printurlonPage() function i get a 0 despite the fact that when i do a console log on the array itself i can see that there are items there. 我发现很难迭代数组,因为当我在printurlonPage()函数上执行array.length时,我得到了0,尽管事实是当我在数组本身上进行控制台日志时我可以看到那里有项目。 Does anyone know a technique that allows me to work on the global variable only after the asynchronous function has completed? 有谁知道一种允许我在异步函数完成后才对全局变量进行操作的技术?

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js" type="text/javascript"></script> <script type="text/javascript"> var PeopleCompleteList = []; function PersonConstructor(username,Title,Phone,Email,imageurl){ return { name: username, Title: Title, phoneNumber: Phone, Email: Email, Picture: imageurl } } var printurlonPage = function (){ for (var link in PeopleCompleteList) { console.log(link['Picture']); } console.log(PeopleCompleteList); } var getIndividualPersonDetails = function(GetPictureUrl) { listName = 'TeamInfo'; //var PeopleCompleteList = []; // execute AJAX request $.ajax({ url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('"+listName+"')/items?$select=Name/Title,Name/Name,Name/Id,Name/EMail,Name/WorkPhone&$expand=Name/Id", type: "GET", headers: { "ACCEPT": "application/json;odata=verbose" }, success: function (data) { for (i=0; i< data.d.results.length; i++) { //check if the user exists if he does store the following properties name,title,workphone,email and picture url if(data.d.results[i]['Name'] != null){ var personName = data.d.results[i]['Name'].Name.split('|')[2]; var userName = data.d.results[i]['Name']['Name']; var UserTitle = data.d.results[i]['Name']['Title']; var UserphoneNumber = data.d.results[i]['Name']['WorkPhone']; var UserEmail = data.d.results[i]['Name']['EMail']; var myuserPicture = GetPictureUrl(userName); console.log(myuserPicture); PeopleCompleteList.push(PersonConstructor(personName, UserTitle, UserphoneNumber,UserEmail,myuserPicture)); } } }, error: function () { alert("Failed to get details"); } }); } function GetPictureUrl(user) { var userPicture=""; var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/SP.UserProfiles.PeopleManager/GetPropertiesFor(accountName=@v)?@v='"+encodeURIComponent(user)+"'"; $.ajax({ url: requestUri, type: "GET", async:false, headers: { "ACCEPT": "application/json;odata=verbose" }, success: function (data) { console.log(data); var PictureDetails = data.d.PictureUrl != null ? data.d.PictureUrl : 'c:\\apps\\noimageurl.jpg'; userPicture=PictureDetails; } }); return userPicture; }; $(function () { getIndividualPersonDetails(GetPictureUrl); printurlonPage(); }); </script> 

You're printurlonPage() is not asynchronous, so it's running before getIndividualPersonDetails responds. 您的printurlonPage()不是异步的,因此它在getIndividualPersonDetails响应之前正在运行。 You can do two things, use promises or use async/await from es7. 您可以做两件事,使用promise或使用es7中的async / await。 I prefer async/await, but you'll need to babelify. 我更喜欢async / await,但是您需要混为一谈。

Or, you can just put your printurlonPage invocation inside your success: handler. 或者,您可以仅将您的printurlonPage调用放入您的success:处理程序中。

    success: function (data) {

        for (i=0; i< data.d.results.length; i++) {
            //check if the user exists if he does store the following properties name,title,workphone,email and picture url
            if(data.d.results[i]['Name'] != null){
                var personName = data.d.results[i]['Name'].Name.split('|')[2];
                var userName = data.d.results[i]['Name']['Name'];
                var UserTitle = data.d.results[i]['Name']['Title'];
                var UserphoneNumber = data.d.results[i]['Name']['WorkPhone'];
                var UserEmail = data.d.results[i]['Name']['EMail'];
                var myuserPicture = GetPictureUrl(userName);
                console.log(myuserPicture);
                PeopleCompleteList.push(PersonConstructor(personName, UserTitle, UserphoneNumber,UserEmail,myuserPicture));
            } 
        }
        printurlonPage();

    },

And then in document.ready: 然后在document.ready中:

$(function () {
    getIndividualPersonDetails(GetPictureUrl);
});

So, getIndividualPersonDetails is invoked, and then when it receives the data, the callback is invoked with the data. 因此,将调用getIndividualPersonDetails,然后在接收到数据时,将与数据一起调用回调。

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

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