簡體   English   中英

訪問從異步函數更新的全局變量

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

我真的很難理解JavaScript的異步方面。 我擁有的代碼旨在整理某些用戶的特定詳細信息,然后將所有整理的信息放入一個全局變量數組中,當所有用戶都添加到該數組時,我打算進行操作。 我發現很難迭代數組,因為當我在printurlonPage()函數上執行array.length時,我得到了0,盡管事實是當我在數組本身上進行控制台日志時我可以看到那里有項目。 有誰知道一種允許我在異步函數完成后才對全局變量進行操作的技術?

 <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> 

您的printurlonPage()不是異步的,因此它在getIndividualPersonDetails響應之前正在運行。 您可以做兩件事,使用promise或使用es7中的async / await。 我更喜歡async / await,但是您需要混為一談。

或者,您可以僅將您的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();

    },

然后在document.ready中:

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

因此,將調用getIndividualPersonDetails,然后在接收到數據時,將與數據一起調用回調。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM