I want to know what is the best way for using JS chaines promises in for SharePoint-Hosted Add-in.
In my code: I have a pageLoad function that's getting data from SP and I want to execute pageLoad first because I use its data in getUserData func.
Code:(App.js)
var clientContext = new SP.ClientContext.get_current();
// Executes when the HTML document is loaded and the DOM is ready
$(document).ready(onPageLoad()); // WHen i call this func in $(function ()
$(function () {
// when i call directly onPageLoad() here, SHe is not implemented..
var promise = onPageLoad();
promise.then(function (currEmpLoginName) {
return getUserData(currEmpLoginName);
}).done(function (sender, args) {
//getLastRecod(listname, userID);
}).fail(function (sender, args) {
// To do something
});
});
function onPageLoad() {
var deferred = $.Deferred();
var user = clientContext.get_web().get_currentUser();
clientContext.load(user);
clientContext.executeQueryAsync(Function.createDelegate(this, successHandler), Function.createDelegate(this, errorHandler));
function successHandler() {
var currEmpDispName = user.get_title();
var badLoginName = user.get_loginName();
currEmpLoginName = badLoginName.substring(badLoginName.lastIndexOf("|") + 1, badLoginName.lastIndexOf("@"));
deferred.resolve(currEmpLoginName);
}
function errorHandler(sender, args) {
var error = args[1].get_message();
deferred.reject(error);
}
return deferred.promise();
}
function getLastRecod(listname, userID){
var deferrend = $.deferrent
//async call
return deferred.promise();
}
Error is:
jQuery.Deferred exception: Unable to get property 'then' of undefined or null reference TypeError: Unable to get property 'then' of undefined or null reference at Anonymous function (https://lirexcom-9cf7bef551a412.sharepoint.com/sites/ioadd/AddHolidayReq/Scripts/App.js:12:5) at j (https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js:2:29941) at Anonymous function (https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js:2:30262) undefined jquery.min.js (2,31515) SCRIPT5007: Unable to get property 'then' of undefined or null reference jquery.min.js (2,31635)
My questions is:
- I want to know if it is well structured code(Accept any estimation).
- What is the best way to call 2nd function where i use her data for getUserData func.
- Where i'm wrong? Thnx..