从另一个函数Ajax,Rest中的函数返回值

时间:2017-01-13 11:42:53

标签: javascript ajax rest

我很难理解为什么下面的代码当pictureRetrieve函数从Completedetails()函数内部调用时返回undefined。尽管知道值存在,特别是当我检查控制台时。在线检查似乎问题可能是由于Ajax的异步性质。它可能是一个我需要改进的领域,但如果有人能够发现问题所在以及如何解决问题,我将不胜感激

function CompleteDetails() {
  var requestUri = _spPageContextInfo.webAbsoluteUrl +
    "/_api/Web/Lists/getByTitle('OrganisationalChart')/items?$select=Id,user/Title,user/Id,user/Name,Boss/Id,Boss/Title,PictureUrl,Designation&$expand=user,Boss";

  $.ajax({
    url: requestUri,
    type: "GET",
    async: false,
    headers: {
      "ACCEPT": "application/json;odata=verbose"
    },
    success: function(data) {

      var dataResults = data.d.results;

      console.log(dataResults);

      for (var i = 0; i < dataResults.length; i++) {
        var userDetails = dataResults[i]['user'].Name.split('|')[1];
        var employeeId = dataResults[i]['user'].Id.toString();
        var employeeName = dataResults[i]['user'].Title
        var Designation = dataResults[i].Designation != null ? dataResults[i].Designation : '';
        var reportingManager = dataResults[i]['Boss']['Id'] != null ? dataResults[i]['Boss']['Id'] : '';
        reportingManager = reportingManager.toString();

        //Get the user profile picture for each user
        userPicture = pictureRetrieve(userDetails);

      }

    },
    failure: function(r) {
      alert(r.d);
    },
    error: function(r) {
      alert(r.d);
    }
  });
}
var pictureRetrieve = function GetPictureUrl(user) {


  var requestUri = _spPageContextInfo.webAbsoluteUrl +
    "/_api/SP.UserProfiles.PeopleManager/GetPropertiesFor(accountName=@v)?@v='" + user + "'";

  $.ajax({

    url: requestUri,
    type: "GET",
    async: false,
    headers: {
      "ACCEPT": "application/json;odata=verbose"
    },
    success: function(data) {


      var DataRes = data.d.PictureUrl;
      var PictureDetails = data.d.PictureUrl != null ? data.d.PictureUrl : 'nouserimageurl';
      console.log(PictureDetails); // i get a value for this everytime it is called;`return PictureDetails;                  


    },
    failure: function(r) {
      alert(r.d);
    },
    error: function(r) {
      alert(r.d);
    }



  });
}

0 个答案:

没有答案