I have a function that submits some data. Depending on the state of some boolean, I might not want to submit this data. However, the caller is always expecting a deferred object as the return value to check .done() or .fail(). It seems you cannot return null or return nothing when something expects done/fail (makes sense), so I don't know how to return from this async call.
I can hack in a $.Deferred object and immediately resolve/return it, but that seems like bad design. I can't change the calling method here.
How can I return a deferred object or some other return value that satisfies .done() or .fail() without using a deferred object?
function foo(a) {
bar(a).done(function () {
console.log("done");
}).fail(function () {
console.log("fail");
});
}
function bar(a) {
if (a){
// Could create a $.Deferred and resolve it
return;
}
return doAsync();
}
function doAsync() {
var defer = $.Deferred();
defer.resolve();
return defer.promise();
}
foo(false); // fine
foo(true); // error
http://jsfiddle.net/ma4grjj4/2/
The main problem is that it's usually a design smell to have boolean arguments that changes the process flow of a function.
I think you will agree that doing something like the following makes no sense:
function process(doNotProcess) {
if (doNotProcess) return;
//process
}
In the above example, it would make more sense to simply not call on process() to avoid processing.
"What I would do ideally is in foo skip the entire call of bar, but a
lot of stuff happens inside of bar().done that needs to occur in both
cases"
That code should probably be factored out of the done callback and put in a different function, which would allow you to reuse it without having to call bar.
"I can hack in a $.Deferred object and immediately resolve/return it,
but that seems like bad design."
Creating deferred objects and resolving them right away is a quite standard approach when you need to standardize the use of an API that may have a synchronous or asynchronous implementation.
It's a very good practice to do so because it frees the client from having to rely on implementation details.
I would like to secure my code to make sure several Ajax requests triggered by user actions in a certain order will have their responses handled in the same order.
I want to keep the asynchonous mechanism of Ajax. Just secure my code to avoid out of sequence responses that can lead to mess on my web page.
To make it perfectly clear. Let's take an example:
$('#button1').click(function(){
$.ajax({url: 'dosomething1.html'})
.done( function(){ console.log('something 1 success'); } )
.fail( function(){ console.log('something 1 failure'); } );
});
$('#button2').click(function(){
$.ajax({url: 'dosomething2.html'})
.done( function(){ console.log('something 2 success'); } )
.fail( function(){ console.log('something 2 failure'); } );
});
$('#button3').click(function(){
$.ajax({url: 'dosomething3.html'})
.done( function(){ console.log('something 3 success'); } )
.fail( function(){ console.log('something 3 failure'); } );
});
If the user clicks on "#button1" then "#button2" and then "button3", I want to see in the console:
>something 1 success
>something 2 success
>something 3 success
It can happen that the responses are not received in the order the server sent them. So I want to get prepared for this scenario.
Note: I can't know in advance the sequence of events triggered by the user. So I need to find a way to chain the response handlers "on the fly".
What would be the best solution to achieve this?
I'm new to Ajax tricky stuff and I read a large amount of things today without finding THE solution (I guess that somehow deferred and promise objects could do the trick).
Please help me to get rid of this terrible headache. :)
Edit to comment the solution by Kevin B.
I struggled with my brain to FULLY understand the example from Kevin B (that does work) until I read a book on Deferreds that explains that the "then" function is actually creating a new Deferred and returns its promise.
This is this new promise that is "chained" to the previous one. It calls its successfull of failure callbacks depending on the result of the previous promise evaluation (resolved or rejected).
In our case that means that when the previous promise is evaluated, the "then" promise is also evaluated and takes as an input the result (resolved or rejected) of the previous promise to decide which callback to call.
In kevin B's code the ajax request promise is returned in both cases (resolved or rejected).
Hence, the .fail and .done callback of the promise are called ONLY ONCE the "then" promise is evaluated AND the returned promise (ajax request one) is "resolved" (.done function) or rejected (.fail function).
To go further:
My understanding is that the promise is a kind of listener on an event that can potentially happen in the future.
In classical cases, when the event happens, the deferred is changed to "resolved" or "rejected" state and the promise callbacks are called.
The promise is "listening" to the state of the deferred to be changed. The event trigerring this state change is the resolution or rejection of the initial event (ajax request, timeout, other...).
In "then" cases, the trigerring event for evaluating the promise is: the referenced promise (previous promise in the chain) is evaluated (either resolved or rejected).
Given the evaluation result, the success or failure callback is called.
I propose this slightly re-organized code inspired by Kevin's code to help out dummies like me to better understand:
var currentPromise = $.Deferred().resolve().promise();
$('#button1').click(function(){
var button1Promise = $.ajax({url: 'dosomething1.html'})
var thenPromise = currentPromise.then(
function () { return button1Promise;},
function () { return button1Promise;}); // to also handle fail conditions gracefully
currentPromise = thenPromise;
// "thenPromise" callback functions are returning the promise linked to
// the ajax request. So this promise is "replacing" the "thenPromise".
// Hence "done" and "fail" functions are finally defined for the ajax request promise.
thenPromise.done( function(){ console.log('something 1 success'); } );
thenPromise.fail( function(){ console.log('something 1 failure'); } );
});
Hopefully it will help people not totally comfortable with jquery concepts to fully understand promises chaining with "then" function.
Don't hesitate to comment if I misundertood something.
If you create a promise up front, you could keep chaining off of it to get your desired effect.
// ajax mock
function sendRequest(v, delay) {
var def = $.Deferred();
setTimeout(function () {
def.resolve(v);
}, delay);
return def.promise();
}
var ajaxPromise = $.Deferred().resolve().promise();
var delay = 600; // will decrement this with each use to simulate later requests finishing sooner
// think of this as a click event handler
function doAction (btnName) {
delay -= 100;
var promise = sendRequest(btnName, delay);
ajaxPromise = ajaxPromise.then(function () {
return promise;
}).done(function () {
console.log(btnName);
});
}
doAction("1");
doAction("2");
doAction("3");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Since i delayed them by 500ms, 400ms, and 300ms, none of them logged until after 500ms.
Here's your code with the same technique:
var ajaxPromise = $.Deferred().resolve().promise();
$('#button1').click(function(){
var promise = $.ajax({url: 'dosomething1.html'})
ajaxPromise = ajaxPromise.then(function () {
return promise;
}, function () {
return promise; // to also handle fail conditions gracefully
}).done( function(){ console.log('something 1 success'); } )
.fail( function(){ console.log('something 1 failure'); } );
});
// repeat for other two buttons
The important thing is all of the ajax requests will always be sent immediately, but the done and fail handlers won't be executed until their turn.
I can't know in advance the sequence of events triggered by the user.
So I need to find a way to chain the response handlers "on the fly".
You need to pipe ajax requests to have the respective responses in the same order, one way to do that is using this plugin https://code.google.com/p/jquery-ajaxq/
As you say:
I can't know in advance the sequence of events triggered by the user. So I need to find a way to chain the response handlers "on the fly".
The right way to go about this is definitely to use deferred objects / promises and NOT set the async parameter to false, which can cause a lot of unwanted problems.
Read the canonical introduction on how to do it here.
EDIT:
An example of synchronizing parallel tasks with $.when(), taken from here:
var promiseOne, promiseTwo, handleSuccess, handleFailure;
// Promises
promiseOne = $.ajax({ url: '../test.html' });
promiseTwo = $.ajax({ url: '../test.html' });
// Success callbacks
// .done() will only run if the promise is successfully resolved
promiseOne.done(function () {
console.log('PromiseOne Done');
});
promiseTwo.done(function () {
console.log('PromiseTwo Done');
});
// $.when() creates a new promise which will be:
// resolved if both promises inside are resolved
// rejected if one of the promises fails
$.when(
promiseOne,
promiseTwo
)
.done(function () {
console.log('promiseOne and promiseTwo are done');
})
.fail(function () {
console.log('One of our promises failed');
});
The easiest way here will be to use async : false parameter for $.AJAX(), just to be sure that your requests run one after another.
http://api.jquery.com/jquery.ajax/
I have code that requires waiting on a variable number of server responses along with loading several javascript modules via requireJS.
I want to leverage jQuery's when.apply. Unfortunately, the .then() portion of my code is always executing before ANY of my callbacks do.
Here is a summary of my code:
// load module func
function loadRequireJsModule(arg, callback) {
require([arg], callback);
}
// get layer info from server func
function getLayerInfoFromServer(arg, callback) {
var layerInfoListener = new DataLayer([arg]);
layerInfoListener.addRetrievedCallback(callback);
layerInfoListener.retrieveLayerInfo();
}
tasks.push( $.Deferred( function() {
loadRequireJsModule( "./" + layerJSON.type, function( module ) {
layer.controller = module;
});
}));
for (i=0; i<layerJSON.views.length; i++) {
layer.views[i] = {};
// get renderer class from require.js
tasks.push( $.Deferred( function() {
loadRequireJsModule( "./impl/" + layerJSON.views[i].renderer, function( index ){
return function( module ) {
layer.views[index].renderer = new module();
}
}(i));
}));
// POST request for layerInfo
tasks.push( $.Deferred( function() {
getLayerInfoFromServer( {
request: "configure",
layer: layerJSON.layer,
configuration: layerJSON.views[i]
}, function( index ){
return function( dataLayer, layerInfo ) {
layer.views[index].dataService = new TileService( layerInfo );
}
}(i));
}));
}
$.when.apply($, tasks).then( function() {
...
}
I'm worried that because my async functions are wrapped, jQuery is simply waiting until those functions end, which is immediate. I cannot pass jquery the naked async functions, they have to be wrapped. What do I have to do in order for my functions to be considered 'deferred objects'?
Edit - now that you've disclosed the actual code:
You are not using $.Deferred() correctly.
A typical usage in your context would look like this:
var d;
var tasks = [];
for (var i = 0; i < len; i++) {
// create new deferred object
d = $.Deferred();
// put deferred into tasks object
tasks.push(d);
loadRequireJsModule( "./impl/" + layerJSON.views[i].renderer, function( index, deferred ){
return function( module ) {
layer.views[index].renderer = new module();
// now that this operation is done, resolve our deferred
deferred.resolve();
}
}(i, d));
}
$.when.apply($, tasks).done(function() {
// code executes here when all the deferreds
// have had `.resolve()` called on them
});
Then, when all deferred objects that were put into the tasks array get resolved (by you calling .resolve()), then $.when() will fire.
You do not generally pass a callback to $.Deferred() like you were doing (that's used for something else and only used in special circumstances where you want to modify the deferred object in certain ways).
You MUST resolve or reject each deferred yourself by calling one of the methods on the deferred object that resolves or rejects it (there are four different methods that can be used).
Also, note that this structure runs ALL the async tasks in parallel (e.g. it fires them all at the beginning and then notifies you at the end when all of them have finished). You would need a different structure if you want them to run sequentially where you don't start the second one until the first has finished and so on.
If you want async behavior, then $.when() expects its arguments to be jQuery deferred or promise objects. So, for the structure of your code to work, the return from myAsyncWrapper() must be a jQuery deferred or promise object. That way, $.when() can monitor the promise objects for completion and when they are all complete, call your .then() handler.
Then, your async operations must either resolve or reject every one of the deferred objects that you passed to $.when() because it will only call its own .done() when ALL the deferred objects you passed to it have been resolved. Or, it will call its own .fail() if any of the deferred objects you passed to it is rejected.
If you are sure all the arguments you are passing to $.when() are deferreds or promises and your .then() handler is still getting called immediately, then your deferreds must already be resolved somehow because that's the likely explanation for why your .then() handler is called immediately.
If none of the arguments passed to $.when() are deferred or promise objects, then it will resolve itself immediately and thus call your .then() handler immediately which sounds like the behavior you are experiencing.
If your async operations are ajax calls, then jQuery.ajax() already returns a promise object that will be resolved when the ajax call completes. You can directly add the return result from jQuery.ajax() to your tasks array and pass that to $.when() and it will support your asynchronous behavior.
Using jQuery.ajax(), here's the concept for using $.when() with multiple concurrent ajax calls:
var promises = [];
for (var i = 0; i < myNum; i++) {
promises.push($.ajax(...));
}
$.when.apply($, promises).done(function() {
// put code here that runs when all the ajax calls have completed
// the results of all the ajax calls are in
// arguments[0], arguments[1], etc...
}).notify(function() {
// .notify is purely optional and only necessary if you want to be notified as
// each async operation completes
// This will get called as each async operation completes with whatever arguments
// were passed to the success handler
}).fail(function() {
// this will get called immediately if any of the async operations failed
// the arguments are the same as the .done() function except that some may be empty
// if they didn't complete before one of them failed
});
Obviously, you don't have to use all three operations .done(), .notify() and .fail() or you can specify all of them in .then() - I just included all three with comments for educational purposes.
If you want help with some other type of async operation that doesn't already create its own promise object, then I'd be happy to help if you show and describe the actual operation. Deferreds are confusing to get a handle on initially, but like many things are actually quite simple and extremely useful once it finally sinks in.
There is an alternative I found for processing a loop of parallel promises without using an array. Instead use the pattern promise = $.when(promise, anotherPromise).
e.g. for you example something like this
// Start with an empty resolved promise - undefined does the same thing!
var promise;
for (i = 0; i < layerJSON.views.length; i++) {
layer.views[i] = {};
// get renderer class from require.js
promise = $.when(promise, loadRequireJsModule("./impl/" + layerJSON.views[i].renderer, function (index) {
return function (module) {
layer.views[index].renderer = new module();
}
}
));
}
// Now do something after all the promises are resolved
promise.then(function () {
// Do the next part
});
This example assumes you change getLayerInfoFromServer to return a promise:
Notes:
The downside of this technique is that the return values of the individual promises are nested within each other, in reverse order, so are not very useful. It is great if you just need to know when it has completed all tasks.
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
});
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.