简体   繁体   中英

How to call combine or call these two functions together?

I am attempting to check if the current user is the owner of the record being edited and if so, I would allow the edit, if not I would prevent the edit. I have two functions that get me the current user and the user who created the record respectively. These are called separately since there are different dependencies. How can I combine these to a single function. Based on a comments below and some debugging, I refactored my code to use promise.all. It is now functioning correctly and is a sample of how to code.

My code is the following:

<!-- Download SPServices from: //spservices.codeplex.com/  -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery.SPServices/2014.02/jquery.SPServices-2014.02.min.js"></script>
<script type="text/javascript">

$(document).ready(function() {
   //don't exectute any jsom until sp.js file has loaded.          
   SP.SOD.executeFunc('sp.js', 'SP.ClientContext', StartProcess);
});

function StartProcess() {  
    var selectedValue = $("h3:contains('Request Phase')").closest('tr').find('select').val();
    if (selectedValue == 'New') {
        const DataFetch = Promise.all([
            makeFirstCall().catch(error => {
                return "error";
            }),
            makeSecondCall().catch(error => {
                return "error";
           })
        ]).then(resolvedData => {
            // do something with resolved data
            console.log('resolvedData='+resolvedData);
        }).catch(error => {
            console.error(error)
           })
        console.log('Succces');
    }
}

const makeFirstCall = () => {
  return new Promise(function(resolve, reject) {
    //console.log('makeFirstCall');
    // make your call
    getCurrentUser().then(
        function (currentUser) {
            var loginId = currentUser.get_id();
            //console.log('Current user ID='+loginId);
            resolve(loginId);
        }
     );
  });
}
const makeSecondCall = () => {
  return new Promise(function(resolve, reject) {
    console.log('makeSecondCall ');
    // make your call
    retrieveListItems().then(
        function (requestUser) {
            //var loginId = requestUser.get_id();
            console.log('requestUser user ID='+requestUser);
            resolve(requestUser);
        }
    );
  });
}

function getCurrentUser()
{
   //Declare your deferred object here  
   //console.log('getCurrentUser');
   var deferred=$.Deferred();  
   var ctx = new SP.ClientContext.get_current();
   this.website = ctx.get_web();
   this.currentUser = website.get_currentUser();
   ctx.load(currentUser);
   ctx.executeQueryAsync(Function.createDelegate(this,
                                                        function () { deferred.resolve(currentUser); }),
                                         Function.createDelegate(this,
                                                       function (sender, args) { deferred.reject(sender, args); })
   );
   //console.log('END-getCurrentUser');
   //Return your Promise Object  
   return deferred.promise();  
}
function retrieveListItems()
{
   //Declare your deferred object here  
   console.log('retrieveListItems');
   var deferred=$.Deferred();  
   var ctx = new SP.ClientContext.get_current();
   // Get ID of the current item.
   var currentItemID = window.location.href.toLowerCase();
   currentItemID = currentItemID.substring(currentItemID.toLowerCase().indexOf("?id=") + 4,
                                                                     currentItemID.toLowerCase().indexOf("&source="));
   console.log('currentItemID='+currentItemID);
   var oList = clientContext.get_web().get_lists().getByTitle('BSMRequests');
   var camlQuery = new SP.CamlQuery();
   camlQuery.set_viewXml('<View><Query><Where><Eq><FieldRef Name=\'ID\'/><Value Type=\'Text\'>'+ currentItemID+
                                          '</Value></Eq></Where></Query></View>'); 
   collListItem = oList.getItems(camlQuery);
   ctx.load(collListItem);
   //var loginId = "66";
   //deferred.resolve(loginId); 
   ctx.executeQueryAsync(Function.createDelegate(this,function () {
                                                        var listItemEnumerator = collListItem.getEnumerator();
                                                        while (listItemEnumerator.moveNext()) {
                                                            var oListItem = listItemEnumerator.get_current();
                                                            console.log('Record id='+oListItem.get_item('ID'));
                                                            requestorID = oListItem.get_item('Requestor_x0020_Name').get_lookupId();
                                                            console.log('requestorID='+requestorID );
                                                        }
                                                        deferred.resolve(requestorID);
                                                        }),
                                         Function.createDelegate(this,function (sender, args) { deferred.reject(sender, args); })
   );
   console.log('END-retrieveListItems');
   //Return your Promise Object  
   return deferred.promise();  
}
</script>

My code will return the two ids and then one can do what they want with those. Those IDs are in an array so comparing them would do the trick.

console.log('Userid: '+resolvedData[0]+'=? Userid: '+resolvedData[1]);

Hi you can make both calls into promises and use promise.all to get the response. That way you wait for both results.

const DataFetch = () => {Promise.all([
  makeFirstCall().catch(error => {
    return "error";
  }),
  makeSecondCall().catch(error => {
    return "error";
  })
]).then(resolvedData => {
 // do something with resolved data
}).catch(error => {
console.error(error)
})}

To make the promise function, you can do this:

const makeFirstCall = () => {
  return new Promise(function(resolve, reject) {
    // make your call
    reject(new Error(`error message`)); // if error
    resolve(dataFromCall);

  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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