Andrew Berry Andrew Berry - 1 month ago 13
Javascript Question

Method being called before Promise is complete

I am attemting to add an item to a sharepoint list from an Apache Cordova application. It first prompts the user to login then it will make a HTTP Post to so the data entry.

I have the following code:

function saveToSharepoint(data) {
var authority = "https://login.microsoftonline.com/common/";
var authContext = new Microsoft.ADAL.AuthenticationContext(authority);
var authResult = authContext.acquireTokenAsync("https://my.sharepoint.com", "4be098f8-2184-4831-9ef7-3d17dbbef6a0", "http://localhost:4400/services/office365/redirectTarget.html")
.then(FormatAndUpload(authResult, data), errorCallback);

}

function FormatAndUpload(authResponse, data) {
var token = authResponse.accessToken;
var expiry = authResponse.expiresOn;
console.log("Token acquired: " + authResponse.accessToken);
console.log("Token will expire on: " + authResponse.expiresOn);
$.ajax({
url: "https://my.sharepoint.com/_api/web/lists/getbytitle('" + Test + "')/items",
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(data),
headers: {
"Accept": "application/json;odata=verbose",
"Authoriztion":"Bearer " + token
},
success: function (data) {
success(data);
},
error: function (data) {
failure(data);
}
});
}


The problem I am having is that the FormatAndUpload method is being called before acquireTokenAsync has completed, so the authResponse variable passed into the FormatAndUpload method is null.

I'm not too familiar with the promise framework in Javascript/JQuery but I was under the impression that the event should only fire on completion of the previous method.

Does anyone have any pointers in how I can correctly wait for the login to complete before attempting the POST?

Answer

what you did FormatAndUpload(authResult, data); is wrong
the correct way to pass a callback is

.then(function(authResult){
    FormatAndUpload(authResult, data);
}, errorCallback);

so your saveToSharepoint will be like this

function saveToSharepoint(data) {
    var authority = "https://login.microsoftonline.com/common/";
    var authContext = new Microsoft.ADAL.AuthenticationContext(authority);
    var authResult = authContext.acquireTokenAsync("https://my.sharepoint.com", "4be098f8-2184-4831-9ef7-3d17dbbef6a0", "http://localhost:4400/services/office365/redirectTarget.html")
    .then(function(authResult){
        FormatAndUpload(authResult, data);
    }, errorCallback);

}
Comments