Thursday 5 September 2019

JSOM

Difference between .Done and .Then in JavaScript?

1. We have one then vs one done, then they work exactly the same. When you have multiple then’s, then things work differently

2. deferred. method returns a new promise.

3. .done fires after the promise resolves and returns the original promise, other dones also get resolved then.


.done: Always returns the same Promise/Wrapped values it started with, regardless of what you do or what you return.

.Then:- Always returns a new promise, and you are in charge of controlling what that promise is based on what the function you passed it returned.


How to get User Profile Properties in SharePoint Online?

  1. <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.0.min.js"></script>  
  2. <script src="/_layouts/15/SP.Runtime.js"></script>  
  3. <script src="/_layouts/15/SP.js"></script>  
  4. <script src="/_layouts/15/SP.UserProfiles.js"></script>

     
  1. <script type="text/javascript">  
  2. (function ($) {  
  3. //debugger;  
  4. $(document).ready(function () {  
  5. // ensure that the SP.UserProfiles.js file is loaded before the custom code runs.  
  6. SP.SOD.executeOrDelayUntilScriptLoaded(loadUserData, 'SP.UserProfiles.js');  
  7. });  
  8. var userProfileProperties;  
  9. function loadUserData()   
  10. {  
  11. //debugger;  
  12. //Get Current Context    
  13. var clientContext = new SP.ClientContext.get_current();  
  14. //Get Instance of People Manager Class  
  15. var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);  
  16. userProfileProperties = peopleManager.getMyProperties();  
  17. clientContext.load(userProfileProperties);  
  18. clientContext.executeQueryAsync(onSuccessful, onFailure);  
  19. }  
  20. function onSuccessful (sender, args) {  
  21. //debugger;  
  22. //Get default properties  
  23. var username = userProfileProperties.get_displayName();  
  24. var desigination = userProfileProperties.get_title();  
  25. var pictureURL = userProfileProperties.get_pictureUrl();  
  26. //Get custom properties  
  27. var employeeID = userProfileProperties.get_userProfileProperties().EmployeeID; 
                


                              JSOM   

1. Used
2. ExecuteQueryAsync()

JSOM or JavaScript Object Model is a set of .js files built for ECMAScript-enabled platforms. The main .js files that are available are:
  • SP.js
  • SP.Core.js
  • SP.Ribbon.js
  • SP.Runtime.js
These files are deployed in the SharePoint15_Root\TEMPLATE\LAYOUTS directory.

    context.Load(listitems);
    context.ExecuteQueryAsync();

Load is to prepare query what you want from the server 
executeQueryAsync/executeQuery is to get the data from the server



Add the following two methods for Callback in App.js
function success() {
    $("#dvMessage").text("Operation Completed Successfully");
}
function fail() {
    $("#dvMessage").text("Operation failed  " + arguments[1].get_message());
}


Syntax:-
{
var clientcontext = sp.clientcontext.get_current();
var website=clientcontext.get_web();
var lists= website.get_lists();
var carlist= lists.getbytitle("cars");
var itemcreatioinfo = new sp.itemcreatioinfo();
var listitem= carlist.additem(itemcreaitoninfo);
    listitem.set_item("title", txtcarname.value);
    listeitem.set_item("carid", txtcarid.value);
    listitem.update();
clientcontext.executequeryAsync(Funtion. createDelegate(This, this.succeded),
                                (Funtion. createDelegate(This, this.failure);
}













Item create into list code:


  1. function AddListItem()  
  2. {  
  3.     var listTitle = 
  4.     
  5.     context = SP.ClientContext.get_current();  
  6.     var airportList = context.get_web().get_lists().getByTitle(listTitle);  
  7.     
  8.     var listItemCreationInformation = 
  9.     var listItem = airportList.addItem(listItemCreationInformation);  
  10.     
  11.     Var industryVal = $(
  12.     var Company = $(
  13.     listItem.set_item(
  14.     listItem.set_item(
  15.     listItem.update();  
  16.     context.load(listItem);  
  17.     context.executeQueryAsync(AddListItemSucceeded, AddListItemFailed);  
  18. }  
  19.   
  20. function AddListItemSucceeded()  
  21. {  
  22.     retriveListItem();  
  23. }  
  24.   
  25. function AddListItemFailed(sender, args)  
  26. {  
  27.     alert(



Get user profile data by Rest API?

4) Get all properties of Specific User:


For Office 365/SharePoint Online:

http://siteurl/_api/SP.UserProfiles.PeopleManager/GetPropertiesFor(accountName=@v)?@v='i:0%23.f|membership|vardhaman@siteurl.onmicrosoft.com'

Get user profile dat by SPFx?





JSOM Convert Async calls to Sync:

SharePoint 2013 Client Object Model is used to retrieve, update and manage the data in SharePoint 2013 library/List. SharePoint makes an Object model available in several forms but here, we are using Javascript Object Model.
  • JavaScript library(JSOM)
  • REST/OData endpoints
In this Javascript Object Model, we will use executeQueryAsync() but it will execute/ will not wait for success/ fail to complete. We need to make executeQueryAsync() behave synchronously.
It means the function will wait for async operations, which should be completed and should return some values.
We know that SharePoint JavaScript Client Object Model is asynchronous. However, sometimes we want to process the things in a synchronous way.
This can be done by using JavaScript callbacks and deferred/Promises. Let's first see an asynchronous example, which we will later convert to synchronous:
For this reason, JavaScript is having an option to use deferred/promise method do this operation.
Promise
The promises pattern significantly simplifies JavaScript code when you make an app, which must have multiple, nested asynchronous calls and it makes it very powerful.
Example
Your JavaScript code has to update multiple list items one by one to complete the basic operations and wait for the first one to execute.
However, Promise object also acts like a caching mechanism, where the success or failure function will be called immediately, if the Promise has already been fulfilled.
Promises object can make it easy to execute dependent asynchronous calls sequentially, which are based on the results.
Syntax
The deferred/ Promise object is very simple syntax and powerful method for sequentially updating in the list/ list items.
Initially, we need to declare the deferred object, as shown below.
  1. var
At the end of the function, we have to return Promise object.
  1. return 
First, we will see about normal JavaScript execution. 
  1. <script type=
  2.     
  3.     $(document).ready(
  4.         
  5.         SP.SOD.executeFunc(
  6.     });  
  7.   
  8.     
  9.         retrivethelistitem(
  10.         console.log(“Execute  second after the retrieve list items ”);              
  11.     }  
  12.   
  13.     
  14.         
  15.         
  16.         
  17.         ocamlItems = olist.getItems(camlQuery);  
  18.         clientContext.load(ocamlItems);  
  19.         clientContext.executeQueryAsync(  
  20.             Function.createDelegate(
  21.             Function.createDelegate(
  22.         );  
  23.     };  
  24.   
  25.     
  26.         
  27.         
  28.             
  29. console.log(‘execute first ‘);  
  30.               
  31. console.log(olistItem.get_item(
  32.         }  
  33.     }  
  34.   
  35.     
  36.         console.log(
  37.     }  
  38. </script>   
Output
For the method given above, we will get the output given below.
Execute second after retrieving the list items.
execute first
NewListitem
Here, we are expecting success function, which should execute first. Unfortunately, the previous one executed. Sometimes it will cause a major issue when you are updating the list items.
Thus, we need to use Async operation to perform synchronously.
Let's see the deferred/ Promise function, as shown below. 
  1. <script type=
  2.     
  3.     $(document).ready(
  4.         
  5.         SP.SOD.executeFunc(
  6.     });  
  7.   
  8.     
  9.         retrivethelistitem(
  10. {  
  11.         console.log(“Execute  second after the retrieve list items ”);   
  12. }).fail(
  13. {  
  14.  console.log(“Execute  second after the retrieve list items  failed”);   
  15. });             
  16.     }  
  17.   
  18.     
  19. //Declare your deferred object here
  20.       
  21.         
  22.         
  23.         
  24.         ocamlItems = olist.getItems(camlQuery);  
  25.         clientContext.load(ocamlItems);  
  26.         clientContext.executeQueryAsync(  
  27.             Function.createDelegate(
  28.             Function.createDelegate(
  29.         );  
  30. //Return your Promise Object
  31. return
  32.     };  
  33.   
  34.     
  35.         
  36.         
  37.             
  38. console.log(‘execute first ‘);  
  39.               
  40. console.log(olistItem.get_item(
  41. //Resolve your object here
  42. deferred.resolve(olistItem );  
  43.         }  
  44.     }  
  45.   
  46.     
  47.         console.log(
  48. //Reject your object here
  49. deferred.reject(olistItem );  
  50.     }  
  51. </script>   
Output
For the code given above, we will get the output, as shown below.
execute first
NewListitem
Execute second after retrieving the list items.

JSOM with AngularJS

Click here



The Deferred and the Promise Objects:




The Deferred object can be employed when performing asynchronous operations, such as Ajax requests and animations. In jQuery, the Promise object is created from a Deferred object or a jQuery object. It possesses a subset of the methods of the Deferred object: always(), done(), fail(), state(), and then(). I’ll cover these methods and others in the next section.

If you’re coming from the native JavaScript world, you might be confused by the existence of these two objects. Why have two objects (Deferred and Promise) when JavaScript has one (Promise)? To explain the difference and their use cases, I’ll adopt the same analogy I’ve used in my book jQuery in Action, third edition.

Deferred objects are typically used if you write the function that deals with asynchronous operations and which should return a value (which can also be an error or no value at all). In this case, your function is the producer of the value and you want to prevent users from changing the state of the Deferred. The promise object is used when you’re the consumer of the function.

To clarify the concept, let’s say that you want to implement a promise-based timeout() function (I’ll show you the code for this example in a following section of this article). You are the one in charge of writing the function that has to wait for a given amount of time (no value is returned in this case). This makes you the producer. The consumer of your function doesn’t care about resolving or rejecting it. The consumer only needs to be able to add functions to execute upon the fulfillment, the failure, or the progress of the Deferred. Moreover, you want to ensure that the consumer isn’t able to resolve or reject the Deferred at their discretion. To achieve this goal, you need to return the Promise object of the Deferred you’ve created in your timeout() function, not the Deferred itself. By doing so, you ensure that nobody can call the resolve() or reject() method except for your timeout() function.

You can read more about the difference between jQuery’s Deferred and Promise objects in this StackOverflow question.

Now that you know what these objects are, let’s take a look at the methods available.

The Deferred Methods
The Deferred object is quite flexible and provides methods for all your needs. It can be created by calling the jQuery.Deferred() method as follows:

var deferred = jQuery.Deferred();
or, using the $ shortcut:

var deferred = $.Deferred();
Once created, the Deferred object exposes several methods. Ignoring those deprecated or removed, they are:

always(callbacks[, callbacks, ..., callbacks]): Add handlers to be called when the Deferred object is either resolved or rejected.
done(callbacks[, callbacks, ..., callbacks]): Add handlers to be called when the Deferred object is resolved.
fail(callbacks[, callbacks, ..., callbacks]): Add handlers to be called when the Deferred object is rejected.
notify([argument, ..., argument]): Call the progressCallbacks on a Deferred object with the given arguments.
notifyWith(context[, argument, ..., argument]): Call the progressCallbacks on a Deferred object with the given context and arguments.
progress(callbacks[, callbacks, ..., callbacks]): Add handlers to be called when the Deferred object generates progress notifications.
promise([target]): Return a Deferred‘s Promise object.
reject([argument, ..., argument]): Reject a Deferred object and call any failCallbacks with the given arguments.
rejectWith(context[, argument, ..., argument]): Reject a Deferred object and call any failCallbacks with the given context and arguments.
resolve([argument, ..., argument]): Resolve a Deferred object and call any doneCallbacks with the given arguments.
resolveWith(context[, argument, ..., argument]): Resolve a Deferred object and call any doneCallbacks with the given context and arguments.
state(): Determine the current state of a Deferred object.

then(resolvedCallback[, rejectedCallback[, progressCallback]]): Add handlers to be called when the Deferred object is resolved, rejected, or still in progress.


Deffered Object is a just javacript object.

but it has property on called Promise which is promise object.

you can pass deffered into Promise Object

Promise have two properties
 1. Status 
 2. Value

by default if you create promise Status is Pending

We can confirm promise object is the exact of promise object as the property on deffered object.
Ex: promise === deffered.promise
true


Deffered object can have two functions
 1. resolve
 2. reject

Promise Object can have two functions/Properties of the promise object.
 1. then
 2. Catch

resolve function:- 
if you think that promise is a progress bar the resolve functiona is saying 
this is no longer in progress, it has completed.

When we resolve the promise, we resolved the value.
that the comes up value of Promise

Once resolve function with output of value then immediatly trigger then() function.

reject function: the value of deffered rejected 






No comments:

Post a Comment