Вернуть текущего пользователя SharePoint 2013, используя Javascript - PullRequest
0 голосов
/ 09 апреля 2020

Я хотел бы узнать, как вернуть значение из одной функции и использовать его в другой. Я могу показать значение в div или получить его в окне предупреждения, но мне нужно использовать значение в другой функции.

<script type="text/javascript">

    SP.SOD.executeOrDelayUntilScriptLoaded(testCase,"sp.js");

    function showUserInfo(){
        var clientContext = SP.ClientContext.get_current();
        var user = clientContext.get_web().get_currentUser();
        clientContext.load(user);
        clientContext.executeQueryAsync(function(){
            return user.get_loginName();
        },function(sender,args){alert(args.get_message());})
    }


    function testCase() {
      var test = showUserInfo(); 
      alert(test);
    }

</script>

Ответы [ 2 ]

0 голосов
/ 12 апреля 2020

Если вам требуется поддержка Inte rnet Explorer

Для поддержки Inte rnet Explorer вам следует использовать функцию обратного вызова, аналогичную предложенной @Amos_MSFT. Ниже вы найдете мое решение, которое очень похоже на решение, опубликованное @Amos_MSFW, но с некоторыми отличиями и комментариями.

// Execute the testCase() function only after sp.js has loaded and is ready.
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function() {
  textCase();
});

function testCase() {
  getLoginName(function(error, success) {
    if (error) {
      alert(error);
    } else {
      /*
       * The line below is not really necessary, as the result of the
       * getLoginName() function is already available in the success
       * variable.  You can already pass it to other functions, like
       * this: alert(success);
       */
      var loginName = success;
      alert(loginName);
    }
  });
}

function getLoginName(callback) {
  var clientContext = SP.ClientContext.get_current();
  var user = clientContext.get_web().get_currentUser();

  clientContext.load(user);
  clientContext.executeQueryAsync(
    function() {
      /*
       * The first argument of the callback() function is used for the
       * error message, so we need to use null as the first argument
       * when we want to return the login name as the success message.
       */
      callback(null, user.get_loginName());
    },
    function(_sender, args) {
      callback(args.get_message());
    }
  );
}

Если вам не нужна поддержка Inte rnet Explorer

Я предлагаю вам использовать Promise , если вам не требуется поддержка Inte rnet Explorer. Обещание - это особый тип объекта, представляющий операцию, которую еще предстоит выполнить, и которая делает работу с асинхронными операциями легкой и почти увлекательной. Я не достаточно беглый, чтобы объяснить их в деталях, поэтому я советую вам прочитать статью, приведенную выше, если вы заинтересованы. Однако я скажу вам, что мы можем использовать Promise, чтобы убедиться, что функция testCase() останавливается и ждет, пока функция showUserInfo() завершит работу sh, как в случае, когда имя для входа будет доступно.

У меня не было возможности протестировать приведенный ниже код, но он должен работать. Если нет, пожалуйста, дайте мне знать. Я также добавил несколько комментариев на случай, если вы еще не знакомы с Обещаниями.

const showUserInfo = () => {
  return new Promise((resolve, reject) => {
    const clientContext = SP.ClientContext.get_current();
    const currentUser = clientContext.get_web().get_currentUser();

    clientContext.load(currentUser);
    clientContext.executeQueryAsync(
      () => {
        /*
         * We resolve the Promise when the query has executed successfully.
         * Resolving a Promise means marking it as fullfilled, or complete, and
         * returning the current user's login name.
         */
        resolve(currentUser.get_loginName());
      },
      (_sender, args) => {
        /*
         * If something goes wrong, we reject the Promise.  Rejecting means
         * marking it as failed, while still returning something.  In this
         * case, we return the error message.
         */
        reject(args.get_message());
      }
    );
  });
}

const testCase = async () => {
  /*
   * We use the await keyword to halt the code and wait for the showUserInfo()
   * function to finish.  What really happens is that we wait for the Promise
   * in the showUserInfo() function to be marked as settled, whether it is
   * fullfilled or rejected, and then assign the result to the test constant.
   */
  const test = await showUserInfo();
  alert(test);
}

SP.SOD.executeOrDelayUntilScriptLoaded(testCase, 'sp.js');
0 голосов
/ 10 апреля 2020

Функция executeQueryAsyn c является асинхронной. Вы можете использовать функцию обратного вызова, чтобы получить возвращаемое значение. Пример кода для вашей справки:

    <script type="text/javascript">
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function(){
  var testCase=function(callback){                             
        var clientContext = SP.ClientContext.get_current();
        var user = clientContext.get_web().get_currentUser();
        clientContext.load(user);
        clientContext.executeQueryAsync(function(){                            
                                callback(null,user.get_loginName()) ;          
        },function(sender,args){alert(args.get_message());})
    }

    testCase(function(error,name){
                if (error) {
    console.error(error);
    return;
  }
  console.log(name);       
                }) 
});
</script>
...