jQuery: What is the difference between deferred.always() and deferred.then()? - javascript

Seems to me that both does the same thing.
Docs:
deferred.always()
deferred.then()

It would seem that deferred.then() allows you to pass two separate callbacks for success and failure, whereas deferred.always() takes n number of callbacks which will all be called regardless of the outcome of the initial event.
I would say use deferred.always() in the cases where success/failure of the initial event are not important

With .then() you can provide an individual callback for when the $.Deferred is resolved (done), and another for when the $.Deferred is rejected (fail).
.always(), on the other hand, allows you to provide a callback that always gets executed, whether the $.Deferred has been resolved or rejected. In other words, within this callback, it doesn't matter if the AJAX call has failed or has been been successfully executed.
I tend to put code in .always() when I want that code to run everytime, and independently of whether the $.Deferred was resolved successfully or not. For example, to clear an AJAX loading indicator or to hide a progress bar. Using .then() you'd have something like this:
$.get("/some/url").then(function () { // done callback
$(".progress-bar").hide();
}, function () { // fail callback
$(".progress-bar").hide();
});
Whilst if you used .always(), you'd just need a single callback, because you always want to hide the progress bar, no matter if the $.Deferred was resolved or rejected:
$.get("/some/url").always(function () {
$(".progress-bar").hide();
});

Prior to jQuery 1.8: .always(fn) is equivalent to .then(fn, fn)
As of jQuery 1.8: .always(fn) is similar to .then(fn, fn) but it differs in what is returned (see http://api.jquery.com/deferred.then/ for details)

The big benefit of then (as of 1.8) is the capability to chain tasks explicitly because it returns a promise which will be resolved with the result of the callback(s)
Example from documentation:
var request = $.ajax( url, { dataType: "json" } ),
chained = request.then(function( data ) {
return $.ajax( url2, { data: { user: data.userId } } );
});
chained.done(function( data ) {
// data retrieved from url2 as provided by the first request
});

Related

Asynchronous jquery - ajax when().then();

I have been trying to read the documents, but I'm having a hard time understanding some concepts:
$.when(function(){
$.ajax({url:'php/Mostrarphp.php', type:'post',data: {queHacer:"MostrarUsuarios"}})
.then(function(success) {
$("#main").html(success);
},function(error) {
$("#main").html(error);
});
})
.then(function() {
console.log("test");
});
What I'm trying to do is for the first function to go into the PHP file and inside that file there is only an include to another file. After that I want to have a console log shown. (This is just practice for, when I need to run functions that retrieve data and will take longer).
The issue here is that the echo is not showing on the application, only shows what is resolved on the then (console.log("test")).
What is the correct way to have this execute the inside function and then the second one?
When you use $.when, you are creating a new promise, one that needs to be resolved. Normally, $.when is used to "combine" multiple promises into one and then run a function once all of them resolve.
What you've passed to $.when is just a function. A function that never gets run. From the docs:
If a single argument is passed to jQuery.when() and it is not a Deferred or a Promise, it will be treated as a resolved Deferred and any doneCallbacks attached will be executed immediately.
So, that means your console.log("test"); is ran, but your AJAX code is never ran.
You do not not to use $.when here. $.ajax already returns a promise, there's no need to make another one. You can just chain .then() calls.
$.ajax({
url:'php/Mostrarphp.php',
type:'post',
data: {queHacer:"MostrarUsuarios"}
}).then(function(success){
$("#main").html(success);
},function(error){
$("#main").html(error);
}).then(function(){
console.log("test");
});
EDIT: In the comments you said:
[no] matter how much time the inside execution takes to complete, the outside [should] always execute second
If this is what you want, then you will need to create another promise. You can do that and then have it resolve once your "inside" function is complete. I'd suggest wrapping your AJAX code in a function and having it return a promise that you can attach a callback to.
function ajaxCall(){
var d = new $.Deferred;
$.ajax({
url:'php/Mostrarphp.php',
type:'post',
data: {queHacer:"MostrarUsuarios"}
}).then(function(success){
setTimeout(function(){
$("#main").html(success);
d.resolve();
}, 2000);
},function(error){
$("#main").html(error);
d.reject();
});
return d.promise();
}
ajaxCall().then(function(){
console.log("test");
});

How to have multiple success callbacks for 1 promise?

I have a function loadItems() that loads something async, and then fails or succeeds. Both fail and success callbacks must do something in the library, and then pass it on to the implementer, which can choose to implement fail, or success, or both, or none.
The problem I now have is if the library implements both the success and fail handler, it will always return a new promise that resolves to success.
This is what I have:
// The library:
function loadItems() {
return store.get('todo').then(function(rsp) {
// Save these locally
items = rsp.value || [];
}, function(rsp) {
// Do nothing, but let the user know
alert(rsp.error);
});
}
store.get('todo') (from yet another library) returns a promise. loadItems() has no control over it.
// The library implementer:
function init() {
loadItems().then(showItems);
}
What I want, and expected to happen:
loadItems() runs the async code from the library (store.get())
It implements success and fail because they have mandatory actions
It passes the success/failure on to the implementer
The implementer only implements success, because it doesn't care about errors, because the library handled it
So it uses .then(onSuccess) to 'add another success callback'
What happens instead (with an error):
The library's failure callback is executed
A new promise is passed on to the implementer
The new promise always resolves with success
The implementer's success callback is fired, with broken result, because the library's success callback didn't fire
Are Promises seriously too cool to have multiple, sync success handlers??
I can imagine even the source library (that defines store.get()) wants to handle the error (for logging sneakily), and then pass success/failure on.
My 'solutions':
Have loadItems()' failure callback throw an error. Unfortunately, that means init() has to catch it (or the browser whines about it). Not cool.
Use a simple callback to talk back to init(), instead of a promise, which only fires after a success. That's not good, because init() might choose to handle the error some day.
I'm sure I'm doing something wrong, but I don't see it.
If you want to have a reject handler to do something based on the error, but want the returned promise to still be rejected, you just rethrow the error (or return a rejected promise) after your reject handling code. This will allow the reject to propagate back through the returned promise.
// The library:
function loadItems() {
return store.get('todo').then(function(rsp) {
// Save these locally
items = rsp.value || [];
}, function(rsp) {
// Do nothing, but let the user know
alert(rsp.error);
// rethrow the error so the returned promise will still be rejected
throw(rsp);
});
}
Supplying a reject handler that does not throw or return a rejected promise tells the promise system that you have "handled" the error and the return value of your reject handler becomes the new fulfilled value of the promise. So, if you want the promise to "stay" rejected, but want to have a handler to do something based on the rejection (logging the rejection is very common), then you have to either rethrow the error in your reject handler or return a rejected promise.
While this may initially seem counter-intuitive, it gives you the most flexibility because you can either completely handle the error and let the returned promise be resolved "successfully" OR you can choose to tell the promise system that you want to propagate an error and you can even choose which error you want that to be (it does not have to be the same error).
The part of your question about multiple success handlers is a bit confusing to me. You can easily have multiple success handlers with any promise:
var p = someFuncThatReturnsSuccessfulPromise();
p.then(someSuccessHandler);
p.then(someOtherSuccessHandler);
If p is a successfully resolved promise, then these two success handlers will both be called in the order they are attached and what happens in someSuccessHandler will have no impact on whether someOtherSuccessHandler is called or not. If the original promise is resolved successfully, then both handlers will always be called.
If you chain your success handlers, then it is a completely different use case. This is completely different:
var p = someFuncThatReturnsSuccessfulPromise();
p.then(someSuccessHandler).then(someOtherSuccessHandler);
Because the second .then() handler is not attached to p, but is attached to p.then(someSuccessHandler) which is a different promise whose outcome is potentially influenced by what happens in someSuccessHandler.
The code in your question is chained. You are returning:
return store.get().then(...)
So, when the caller then chains onto that, the full chain is:
return store.get().then(yourhandler).then(theirhandler)
In this way, yourhandler can influence the outcome that is passed to theirhandler.
In addition to my first recommendation of just rethrowing the error, you could also have done this:
// The library:
function loadItems() {
var p = store.get('todo');
p.then(function(rsp) {
// Save these locally
items = rsp.value || [];
}, function(rsp) {
// Do nothing, but let the user know
alert(rsp.error);
});
return p;
}
Here you ware making sure that your handlers don't affect what is being returned. This can be done if you don't have any async operations in your handlers and you aren't trying to change the resolved value or rejected error of the original store.get() promise. I generally don't recommend this because it is a cause for problems if your handlers are doing other async things or want to influence the return values, but it can also be used in appropriate circumstances.

Force jQuery Deferred to wait until Ajax complete in "then" handler

I have situation where I believe I need to create a Deferred object with a "then" handler, but wait until the "then" handler has completed it's own promise before moving on.
The use case is a record object, and the above function is it's save method. The record object has an attribute called saveQueue, which is set to $.Deferred() on the record's instantiation. The resolve call on saveQueue was supposed to make sure the Deferred there is always executing every new handler attached to it as soon as it could. The idea being that you can call save several times on the record in short succession, but the calls will run one after another, and not overlap.
I am using a Deferred to enqueue Ajax calls, so that one does not run until the previous one call finished. However, from the same method, I want to return a Deferred that can be resolved/rejected by the jQuery Ajax object, like so:
record.saveQueue = $.Deferred();
self.save = function( record ){
var deferredAction = $.Deferred();
deferredAction.then(function() {
return $.post("/example_save_endpoint");
});
record.saveQueue.always(function(){
deferredAction.resolve();
}).resolve();
return deferredAction;
}
However, when I use this code, the deferredAction promise always ends up resolved, presumably because the #then handler is returning a "pending" (and thus non-rejecting) promise. Is there any way to force the Deferred to wait until the Ajax promise is complete before resolving/rejecting? Or is there another, better way to thread this needle?
Your idea might work, but
the queue must not be resolved using .resolve() every time the method is called, instead it should be initialised only with a resolved promise.
to actually queue on the record.saveQueue, it needs to be changed (overwritten) on every method call, to represent the end of the latest request.
And we don't need any deferreds for that, as we can work with the promises that $.post returns.
So use this:
var emptyQueue = $.when(undefined); // an already fulfilled promise as the start
// equivalent: = $.Deferred().resolve().promise();
function startQueue() {
return emptyQueue; // yes, this delibaretely returns a constant, the begin
// of the queue always looks the same (and is never mutated)
}
// every time you create a record, do
record.saveQueue = startQueue();
// and use that in your methods:
this.save = function(record) {
var queuedRequestResult = record.saveQueue.then(function() {
return $.post("/example_save_endpoint");
// ^^^^^^ promises chain :-)
});
// Magic happens here:
record.saveQueue = queuedRequestResult // we swap the previous queue promise for a new
// one that resolves only after the request
.then(startQueue, startQueue); // and make sure it then starts with a fresh
// queue, especially when the request failed
//.then(null, startQueue) is similar, except unnecessarily remembering the last result
return queuedRequestResult;
}
I would probably choose not to do it this way, but a deferred/promise can indeed be used as a queuing device.
You need a slight(?) variation of what you already tried.
self.queue = $.when();//A resolved promise, used to form a queue of functions in a .then() chain.
self.save = function(data) {
var dfrd = $.Deferred();//A Deferred dedicated to this particular save.
self.queue = self.queue.then(function() {
return $.post("/example_save_endpoint", data) //Make the AJAX call, and return a jqXHR to ensure the downstream queue waits for this jqXHR to resolve/reject.
.then(dfrd.resolve, dfrd.reject) //Resolve/reject the Deferred for the caller's benefit
.then(null, function() {
//Force failure down the success path to ensure the queue is not killed by an AJAX failure.
return $.when();//Return a resolved promsie, for the queue's benefit.
});
});
return dfrd.promise();//allow the caller to do something when the AJAX eventually responds
}
For explanation, see comments in code

jQuery Deferred's, $.when() and the fail() callback arguments

I'm getting an unexpected result when using $.when() when one of the deferred operations does not succeed.
Take this JavaScript, which created 2 deferreds. The first one succeeds and the second one fails.
var f1 = function() {
return $.Deferred(function(dfd) {
dfd.resolve('123 from f1');
}).promise();
};
var f2 = function() {
return $.Deferred(function(dfd) {
dfd.reject('456 from f2');
}).promise();
};
$.when(f1(), f2())
.then(function(f1Val, f2Val) {
alert('success! f1, f2: ' + JSON.stringify([f1Val, f2Val]));
})
.fail(function(f1Val, f2Val) {
alert('fail! f1, f2: ' + JSON.stringify([f1Val, f2Val]));
});
Run it yourself: http://jsfiddle.net/r2d3j/2/
I get fail! f1, f2: ["456 from f2", null]
The problem is that in the .fail() callback the value passed with the f2() rejection, is being routed to the first argument, where i expect the f1Value. Which means that I don't really have a way of know which deferred object actually posted that reject(), and I also dont know which operation that failure data actually belongs to.
I would have expected that .fail() would get arguments null, '456 from f2' since the first deferred did not fail. Or am I just not doing deferreds right way here?
How do I know which deferreds failed, and which rejection arguments belong to which failed deferred if the argument order in the callback is not respected?
$.when() will execute the failed callback (2nd parameter passed to then()) immediately if any one of the parameters fails. It's by design. To quote the documentation:
http://api.jquery.com/jQuery.when/
In the multiple-Deferreds case where one of the Deferreds is rejected, jQuery.when immediately fires the failCallbacks for its master Deferred. Note that some of the Deferreds may still be unresolved at that point. If you need to perform additional processing for this case, such as canceling any unfinished ajax requests, you can keep references to the underlying jqXHR objects in a closure and inspect/cancel them in the failCallback.
There's actually no built-in way of getting a callback that waits untils all of them are finished regardless of their success/failure status.
So, I built a $.whenAll() for you :)
It always waits until all of them resolve, one way or the other:
http://jsfiddle.net/InfinitiesLoop/yQsYK/51/
$.whenAll(a, b, c)
.then( callbackUponAllResolvedOrRejected );
Internally, the "reject" and "fail" paths are handled by two totally separate queues, so it just doesn't work the way you expect.
In order to know which original Deferred failed from the "when()" group, you could have them pass themselves along with the ".reject()" call as part of an object literal or something.
I've faced this same problem, and I dealt with it by using the .always callback and inspecting my array of deferred objects. I had an unknown number of ajax calls, so I had to do the following:
// array of ajax deletes
var deletes = [];
$checkboxes.each(function () {
deletes.push(deleteFile(this));
});
$.when.apply($, deletes)
.always(function () {
// unfortunately .fail shortcircuits and returns the first fail,
// so we have to loop the deferred objects and see what happened.
$.each(deletes, function () {
this.done(function () {
console.log("done");
}).fail(function () {
console.log("fail");
});
});
});
The deleteFile method returns a promise, which has .done or .fail callbacks.
This allows you to take action after all deferreds have completed. In my case I'm going to show a delete file error summary.
I just tried this, and unfortunately I had to put a interval timer to check that they were all truly done after my $.each on the deferred objects. This seems odd and counterintuitive.
Still trying to understand these deferreds!
Very old question but now, to wait until all are resolved, you can use Promise.allSettled since $.ajax deals with standard promises.
The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise
Therefore you can use
Promise.allSettled([$.ajax(), $.ajax()])
.then((res) => {
if (res[0].status === 'fulfilled') {
console.log(res[0].value)
// do something
} else {
console.error('res1 unavailable')
}
if (res[1].status === 'fulfilled') {
console.log(res[1].value)
// do something
} else {
console.error('res2 unavailable')
}
})

What does the function then() mean in JavaScript?

I’ve been seeing code that looks like:
myObj.doSome("task").then(function(env) {
// logic
});
Where does then() come from?
The traditional way to deal with asynchronous calls in JavaScript has been with callbacks.
Say we had to make three calls to the server, one after the other, to set up our
application. With callbacks, the code might look something like the following (assuming
a xhrGET function to make the server call):
// Fetch some server configuration
xhrGET('/api/server-config', function(config) {
// Fetch the user information, if he's logged in
xhrGET('/api/' + config.USER_END_POINT, function(user) {
// Fetch the items for the user
xhrGET('/api/' + user.id + '/items', function(items) {
// Actually display the items here
});
});
});
In this example, we first fetch the server configuration. Then based on that, we fetch
information about the current user, and then finally get the list of items for the current
user. Each xhrGET call takes a callback function that is executed when the server
responds.
Now of course the more levels of nesting we have, the harder the code is to read, debug,
maintain, upgrade, and basically work with. This is generally known as callback hell.
Also, if we needed to handle errors, we need to possibly pass in another function to each
xhrGET call to tell it what it needs to do in case of an error. If we wanted to have just one
common error handler, that is not possible.
The Promise API was designed to solve this nesting problem and the
problem of error handling.
The Promise API proposes the following:
Each asynchronous task will return a promise object.
Each promise object will have a then function that can take two arguments, a success
handler and an error handler.
The success or the error handler in the then function will be called only once, after
the asynchronous task finishes.
The then function will also return a promise, to allow chaining multiple calls.
Each handler (success or error) can return a value, which will be passed to the next
function as an argument, in the chain of promises.
If a handler returns a promise (makes another asynchronous request), then the next
handler (success or error) will be called only after that request is finished.
So the previous example code might translate to something like the following, using
promises and the $http service(in AngularJs):
$http.get('/api/server-config').then(
function(configResponse) {
return $http.get('/api/' + configResponse.data.USER_END_POINT);
}
).then(
function(userResponse) {
return $http.get('/api/' + userResponse.data.id + '/items');
}
).then(
function(itemResponse) {
// Display items here
},
function(error) {
// Common error handling
}
);
Propagating Success and Error
Chaining promises is a very powerful technique that allows us to accomplish a lot of
functionality, like having a service make a server call, do some postprocessing of the
data, and then return the processed data to the controller. But when we work with
promise chains, there are a few things we need to keep in mind.
Consider the following hypothetical promise chain with three promises, P1, P2, and P3.
Each promise has a success handler and an error handler, so S1 and E1 for P1, S2 and
E2 for P2, and S3 and E3 for P3:
xhrCall()
.then(S1, E1) //P1
.then(S2, E2) //P2
.then(S3, E3) //P3
In the normal flow of things, where there are no errors, the application would flow
through S1, S2, and finally, S3. But in real life, things are never that smooth. P1 might
encounter an error, or P2 might encounter an error, triggering E1 or E2.
Consider the following cases:
• We receive a successful response from the server in P1, but the data returned is not
correct, or there is no data available on the server (think empty array). In such a
case, for the next promise P2, it should trigger the error handler E2.
• We receive an error for promise P2, triggering E2. But inside the handler, we have
data from the cache, ensuring that the application can load as normal. In that case,
we might want to ensure that after E2, S3 is called.
So each time we write a success or an error handler, we need to make a call—given our
current function, is this promise a success or a failure for the next handler in the promise
chain?
If we want to trigger the success handler for the next promise in the chain, we can just
return a value from the success or the error handler
If, on the other hand, we want to trigger the error handler for the next promise in the
chain, we can do that using a deferred object and calling its reject() method
Now What is deferred object?
Deferred objects in jQuery represents a unit of work that will be
completed later, typically asynchronously. Once the unit of work
completes, the deferred object can be set to resolved or failed.
A deferred object contains a promise object. Via the promise object
you can specify what is to happen when the unit of work completes. You
do so by setting callback functions on the promise object.
Deferred objects in Jquery : https://api.jquery.com/jquery.deferred/
Deferred objects in AngularJs : https://docs.angularjs.org/api/ng/service/$q
then() function is related to "Javascript promises" that are used in some libraries or frameworks like jQuery or AngularJS.
A promise is a pattern for handling asynchronous operations. The promise allows you to call a method called "then" that lets you specify the function(s) to use as the callbacks.
For more information see: http://wildermuth.com/2013/8/3/JavaScript_Promises
And for Angular promises: http://liamkaufman.com/blog/2013/09/09/using-angularjs-promises/
As of ECMAScript6
The .then() method has been included with pure JavaScript with Promises.
From the Mozilla documentation:
The then() method returns a Promise. It takes two arguments: callback
functions for the success and failure cases of the Promise.
The Promise object, in turn, is defined as
The Promise object is used for deferred and asynchronous
computations. A Promise represents an operation that hasn't completed
yet, but is expected in the future.
That is, the Promise acts as a placeholder for a value that is not yet computed, but shall be resolved in the future. And the .then() function is used to associate the functions to be invoked on the Promise when it is resolved - either as a success or a failure.
Before ECMAScript6
To my knowledge, there isn't a built-in then() method in javascript (at the time of this writing).
It appears that whatever it is that doSome("task") is returning has a method called then.
If you log the return result of doSome() to the console, you should be able to see the properties of what was returned.
console.log( myObj.doSome("task") ); // Expand the returned object in the
// console to see its properties.
Here is a thing I made for myself to clear out how things work. I guess others too can find this concrete example useful:
doit().then(function() { log('Now finally done!') });
log('---- But notice where this ends up!');
// For pedagogical reasons I originally wrote the following doit()-function so that
// it was clear that it is a promise. That way wasn't really a normal way to do
// it though, and therefore Slikts edited my answer. I therefore now want to remind
// you here that the return value of the following function is a promise, because
// it is an async function (every async function returns a promise).
async function doit() {
log('Calling someTimeConsumingThing');
await someTimeConsumingThing();
log('Ready with someTimeConsumingThing');
}
function someTimeConsumingThing() {
return new Promise(function(resolve,reject) {
setTimeout(resolve, 2000);
})
}
function log(txt) {
document.getElementById('msg').innerHTML += txt + '<br>'
}
<div id='msg'></div>
Here is a small JS_Fiddle.
then is a method callback stack which is available after a promise is resolved it is part of library like jQuery but now it is available in native JavaScript and below is the detail explanation how it works
You can do a Promise in native JavaScript : just like there are promises in jQuery, Every promise can be stacked and then can be called with Resolve and Reject callbacks, This is how you can chain asynchronous calls.
I forked and Edited from MSDN Docs on Battery charging status..
What this does is try to find out if user laptop or device is charging battery. then is called and you can do your work post success.
navigator
.getBattery()
.then(function(battery) {
var charging = battery.charging;
alert(charging);
})
.then(function(){alert("YeoMan : SINGH is King !!");});
Another es6 Example
function fetchAsync (url, timeout, onData, onError) {
…
}
let fetchPromised = (url, timeout) => {
return new Promise((resolve, reject) => {
fetchAsync(url, timeout, resolve, reject)
})
}
Promise.all([
fetchPromised("http://backend/foo.txt", 500),
fetchPromised("http://backend/bar.txt", 500),
fetchPromised("http://backend/baz.txt", 500)
]).then((data) => {
let [ foo, bar, baz ] = data
console.log(`success: foo=${foo} bar=${bar} baz=${baz}`)
}, (err) => {
console.log(`error: ${err}`)
})
Definition :: then is a method used to solve Asynchronous callbacks
this is introduced in ES6
Please find the proper documentation here Es6 Promises
.then returns a promise in async function.
Good Example would be:
var doSome = new Promise(function(resolve, reject){
resolve('I am doing something');
});
doSome.then(function(value){
console.log(value);
});
To add another logic to it, you can also add the reject('I am the rejected param') call the function and console.log it.
It's about the use of curly braces {} in our arrow functions:
Those 3 examples are doing the same thing (nothing, but have valid grammar, and are a valid Promise chain!)
new Promise(function(ok) {
ok(
/* myFunc1(param1, param2, ..) */
)
}).then(function(){
/* myFunc1 succeed */
/* Launch something else */
/* console.log(whateverparam1) */
/* myFunc2(whateverparam1, otherparam, ..) */
}).then(function(){
/* myFunc2 succeed */
/* Launch something else */
/* myFunc3(whatever38, ..) */
})
console.log("This code has no errors GG!")
The same logic using arrow functions shorthand without {}
new Promise((ok) =>
ok(
/* myFunc1(param1, param2, ..) */
).then(() =>
0 // HEY DID YOU NOTICE! A number that does nothing,
// but otherwise the parsing will fail!
// The code is pretty clean but have a major downside
// As arrow functions without {} can contains only one declaration
// console.log("something") will FAIL here
).then(() =>
"" // HEY DID YOU NOTICE! An empty string that does nothing,
// but otherwise the parsing will fail!
// As arrow functions without {} can contains only one declaration
// We can't add more code here, hence:
// console.log("something")
// Will break the whole promise
// This is likely the error in y(our) code ;)
))
console.log("This code has no errors GG!")
Arrow function with {}
new Promise( (ok) => {
ok(
/* myFunc1(param1, param2, ..) */
)
}).then( () => {
/* myFunc1 succeed */
/* Launch something else */
}).then( () => {
/* myFunc2 succeed */
/* Launch something else */
/* myFunc3(whatever38, ..) */
console.log("something")
/* More console logs! */
console.log("something else")
})
console.log("This code has no errors GG!")
I suspect doSome returns this, which is myObj, which also has a then method. Standard method chaining...
if doSome is not returning this, being the object on which doSome was executed, rest assured it is returning some object with a then method...
as #patrick points out, there is no then() for standard js
doSome("task")must be returning a promise object , and that promise always have a then function .So your code is just like this
promise.then(function(env) {
// logic
});
and you know this is just an ordinary call to member function .
In this case then() is a class method of the object returned by doSome() method.
The ".then()" function is wideley used for promised objects in Asynchoronus programming For Windows 8 Store Apps.
As far as i understood it works some way like a callback.
Find Details in this Documentantion
http://msdn.microsoft.com/en-us/library/windows/apps/hh700330.aspx
Of Cause it could also be the name for any other defined function.
I am about 8 years late, well...anyways, I don't really know what then() does but maybe MDN might have an answer. Actually, I might actually understand it a little more.
This will show you all the information (hopefully), you need. Unless someone already posted this link.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then
The format is promise.prototype.then()
The promise and prototype are kind of like variables but not like variables in javascript, I mean like other things go there like navigator.getBattery().then() where this one actually exists but is barely used on the web, this one shows statuses about the battery of the device, more information and more on MDN if you are curious.

Categories