PDA

View Full Version : What does ".then" mean in JavaScript?



Space Admiral Xarzu
02-23-2018, 02:03 AM
What does ".then" mean in JavaScript?

Consider this snippet of code:



return ajaxService.request('post', 'api/{ticketId}/alt-forms/getSatelliteMapUrl', geoCodedata, { failureMessage: 'Failed to Geocode SatMap/PDF'})
.then(function (satelliteMapData, data) {

Is the ".then" comment attached immediately to the previous "return" statement? If so, how? If not, then would the functionality of this JavaScript bit not be impacted if I put an "alert" statement immediately before the ".then" statement and immediately after the "return" statement?

Deadweight
02-23-2018, 02:24 AM
I think this will help you:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then

jscheuer1
02-23-2018, 02:27 AM
It's not always applicable. When it is, it either means (if unqualified) "on success", or if qualified by an indication of then in which case (situation), then in that case. In the context in which you have presented it in your post, most likely it means in case the ajax call is successful, then execute a function (only the beginning of which is shown in your post):


function (satelliteMapData, data) {

Which is also dependent upon other code as to what exactly that means. Likely it means to map some data either to a data base, or more likely in this case, to a graphic map of some kind on the page, or perhaps, since PDF is mentioned, to a PDF file somewhere.

And to answer your other question, yes. It is immediately dependent upon the previous line, in fact a continuation of it. The two lines could as easily be written:


return ajaxService.request('post', 'api/{ticketId}/alt-forms/getSatelliteMapUrl', geoCodedata, { failureMessage: 'Failed to Geocode SatMap/PDF'}).then(function (satelliteMapData, data) {

So, no. You cannot interpose an alert in there without breaking the code. If you wanted to test things you could temporarily change it to:


return ajaxService.request('post', 'api/{ticketId}/alt-forms/getSatelliteMapUrl', geoCodedata, { failureMessage: 'Failed to Geocode SatMap/PDF'})
.then(function (satelliteMapData, data) {alert(data);

That would give you some idea of what 'data' represents. Probably an object though, so if you work with the console at all, more information could be got there by:


return ajaxService.request('post', 'api/{ticketId}/alt-forms/getSatelliteMapUrl', geoCodedata, { failureMessage: 'Failed to Geocode SatMap/PDF'})
.then(function (satelliteMapData, data) {console.log(data);

In any case, it's in the unseen in your post following lines of code that 'data' is utilized. Most likely by the satelliteMapData function, but we cannot know that for certain from such a small amount of code.