How to make Rest API call synchronous in SharePoint
How to make Rest API call synchronous in SharePoint
In this post, I will discuss how we can make a synchronous Rest API call in SharePoint using jQuery. Normally when we do Rest API call using AJAX calls in SharePoint, it executed asynchronously. So it is not possible to know whether the call has been made completely or not. Sometimes you might come across a requirement where you want to execute something after the call has been made complete.
Here I will show some ways of make synchronous Rest API call in SharePoint -
1. Using then -
getItems().then(getItemsSuccess, getItemsFail);
function getItems(){
return $.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('ListName')/items",
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
}
});
}
function getItemsSuccess(data){
if(data.d.results.length > 0){
//do something here //
}
}
function getItemsFail(err){
alert("Some error occurred !!!");
}
2. Using done -
getItems( ).done(function(data){
// do something here //
});
3. Using Deferred -
function getListItemWithId(itemId, listName, siteurl, success, failure) {
var d = $.Deferred();
var url = siteurl + "/_api/web/lists/getbytitle('" + listName + "')/items?$filter=Id eq " + itemId;
$.ajax({
url: url,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
d.resolve(data.d.results);
},
error: function (data) {
failure(data);
d.reject;
}
});
return d.promise();
}
getListItemWithId(itemId, listName, siteurl).done(success).fail(error);
function success(data){
//perform your logic in here.
}
function error(data){
//Show your error Here
}
I hope using these approaches you can make a rest api call synchronous.
Comments
Post a Comment