I use in my application a request REST API which works asynchronous. How I can do to know the request is done?
2 Answers
Ajax/REST calls do let know when they succeed or fail, that is the whole point.
And you do not need to convert code to synchronous calls.
In the old days you would use Callback functions, nowadays you use Promises
(you can even mix these, Callbacks are executed first)
The best post explaining all this async stuff is:
(it has 2757 upvotes, you can +1)
https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call
Code
because Link-only posts are not encouraged and the admins are watching me
orginally from a jQuery answer
Here is code with both Callback functions and Methods chained to the $.ajax Promise
learn to use Chrome Snippets to run SP code without going through a long & complex built proces
console.clear();
var site=_spPageContextInfo.webAbsoluteUrl;
var listName='Documents';
$.ajax({
url: site + "/_api/web/lists/getbytitle('" + listName + "')",
method: "GET",
contentType: "application/json;odata=verbose",
async: true, // is the default value, so you can leave it out
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success:function(data){//this is a Callback function
console.log('success Callback', data)
},
error:function(data){//this is a Callback function
console.log('error Callback', data)
}
}).done(function(data){//this is a method on the Promise chain
console.log('success ',data);
}).fail(function(data){//this is a method on the Promise chain
console.error('error ',data);
}).always(function(data){//this is a method on the Promise chain
console.log('always ',data);
});
So the .done method is interchangable with the success Callback
Note that they are both executed in this example.. Callbacks first.
(modern) Promises are more powerful, (oldschool) Callbacks are used in most blogposts.
I had to RTFM as well
.success
and .error
methods you see in blogposts are deprecated since jQuery 1.8 (use .done
and .fail
) but do still work
Yes you can do ajax without jQuery
You do not need that 90KB library, it is just a fancy wrapper around native JavaScript code:
var site=_spPageContextInfo.webAbsoluteUrl,
listName='Documents',
xhr = new XMLHttpRequest();
xhr.open("GET",site+"/_api/web/lists/getbytitle('"+listName+"')", true);
xhr.setRequestHeader("Accept","application/json;odata=nometadata");
xhr.setRequestHeader("X-RequestDigest",document.getElementById('__REQUESTDIGEST').value);
xhr.onreadystatechange = function (data) {
if (xhr.readyState != 4) return;//no response received yet
if (xhr.status===200) console.info('success');
console.info('I got:',listName,data);
};
xhr.send();
A modern replacement for XMLHttpRequest
is fetch
, but it does have some drawbacks: https://davidwalsh.name/fetch
You do need a polyfill becuase only Microsoft Edge 14 now supports it.
Promises are native JavaScript as well but also require a polyfill, Edge is fine but IE still stinks.
Note that jQuery does done
and fail
, native JS is then
and catch
When diving deeper into REST, be sure to understand the different odata responses: https://blogs.office.com/2014/08/13/json-light-support-rest-sharepoint-api-released/
Microsoft is pushing an open-source team to write a wrapper around SP-REST functionality. https://github.com/OfficeDev/PnP-JS-Core
(Remember: this does require Promise & Fetch polyfills to run)
Stackoverflow related posts:
- Differing ways to make executeQueryAsync calls - Function.createDelegate (is old IE8 code)
Explains how to pass data to a succeed function, and whycreateDelegate
is pointless nowadays
iJS iREST
-
1This answers only the case when you use JavaScript... Commented Sep 5, 2016 at 8:05
-
Correct. But you have not been around for nearly 2 years, Wictor (i.imgur.com/TOr2bHk.jpg) If someone asks a REST question here on SO, and they tag it 'online' I will go all-in with my SO-points it is a JavaScript question. (btw. +1 for spelling JavaScript correct 😉 Commented Sep 5, 2016 at 8:14
-
-
It wouldn't be a bad idea, some more gamification/poker with SO credits. Current system sucks. Commented Sep 5, 2016 at 8:34
-
Love that you saved old pictures of my SO points! Commented Sep 5, 2016 at 8:35
There's no acknowledgement of asynchronous requests, it's kind of the point. If you want to know if the request succeeds or fails you either have to change your code to synchronous operations OR use asynchronous methods in your code to wait for the response (exactly how, depends on where your code is executing; JavaScript, C# etc).
async:false,