0

我試圖從Apache Cordova應用程序中將項目添加到共享點列表。它首先提示用戶登錄,然後它會創建一個HTTP Post來輸入數據。在Promise完成之前調用方法

我有以下代碼:

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); 
     } 
    }); 
} 

我遇到的問題是,acquireTokenAsync完成之前被稱爲FormatAndUpload方法,所以傳遞到FormatAndUpload方法authResponse變量爲空。

我不太熟悉JavaScript/JQuery中的承諾框架,但我的印象是事件只應在完成前面的方法時觸發。

有沒有人有任何指示我如何在嘗試POST之前正確等待登錄完成?

回答

1

你做了什麼FormatAndUpload(authResult,data);是錯誤的
傳遞一個回調正確的方法是

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

所以你saveToSharepoint會是這樣

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); 

} 
0

感謝您的回答Newbee開發,你是正確的,我並沒有制定然後方法正確。

對於誰看到這方面的SharePoint任何別人,其實我重新格式化代碼,按預期的方式工作,所以saveToSharepoint方法看起來像這樣:

function saveToSharepoint(data) { 
var AuthenticationContext = Microsoft.ADAL.AuthenticationContext; 
AuthenticationContext.createAsync("https://login.microsoftonline.com/common/") 
    .then(function (authContext) { 
     authContext.acquireTokenAsync(
      "https://my.sharepoint.com",  // Resource URI 
      "4be098f8-2184-4831-9ef7-3d17dbbef6a0",  // Client ID 
      "http://localhost:4400/services/office365/redirectTarget.html" // Redirect URI 
     ).then(function (authResult) { 
      FormatAndUpload(authResult, data); 
     }, function (err) { 
      console.log(err); 
     }); 
    }, function (err) { 
     console.log(err); 
    }); 
} 

要注意的是異步創建AuthenticationContext最主要的這樣,整個登錄過程完成後,FormatAndUpload調用完成。只是以爲我會張貼這個看到這個關於Sharepoint的其他人,並卡住了。

相關問題