Deferred
An implementation of OCaml's Deferred for Swift.
I'm digging into jQuery's deferred features. I've tried several examples on the internet. I understood its concept, but I don't understand the difference between resolve()
and promise()
.
What are differences between resolve()
and promise()
?
Source: (StackOverflow)
I've a long-running task defined in spring service, it is started by springmvc controller. I want to start service and return back an HttpResponse to caller before service ends. The service saves a file on file system at end.
In javascript I've created a polling job to check service status.
In Spring 3.2 I've found @Async annontation, but I don't understand how it is different from DeferredResult and Callable. When do I have to use @Async? and when do I use DeferredResult?
Source: (StackOverflow)
In my Angular.js application, I'm running some asynchronous operation. Before it starts I cover the application with a modal div, then once the operation is complete, I need to remove the div, whether the operation was successful or not.
Currently I have this:
LoadingOverlay.start();
Auth.initialize().then(function() {
LoadingOverlay.stop();
}, function() {
LoadingOverlay.stop(); // Code needs to be duplicated here
})
It works well, however I would prefer to have something cleaner like this pseudo-code:
LoadingOverlay.start();
Auth.initialize().finally(function() { // *pseudo-code* - some function that is always executed on both failure and success.
LoadingOverlay.stop();
})
I assume it's quite a common problem, so I was thinking it could be done but cannot find anything in the doc. Any idea if it can be done?
Source: (StackOverflow)
I have configured some basic routes that are available for all users before they log in:
App.config(function ($routeProvider) {
$routeProvider.
when('/login', { templateUrl: 'views/login.html', controller: PageStartCtrl.Controller }).
otherwise({ redirectTo: '/login' });
});
So the only thing user can do is to log in. After the user logs in, I would like to register additional routes like this:
$http
.post('api/Users/Login', { User: userName, Password: userPassword })
.success(function (response : any) {
App.config(function ($routeProvider) {
$routeProvider
.when('/dashboard',
{ templateUrl: 'part/dashboard.html',
controller: DashboardCtrl.Controller });
});
However, I suppose I should call .config method only once, because the $routeProvider is brand new instance that knows nothing about /login route. Further debugging showed me that the first instance of $resourceProvider is used when resolving view change.
Q: Is there a way how to register routes later?
Solution from Add routes and templates dynamically to $routeProvider might work, but is quite ugly (involved global variable nastyGlobalReferenceToRouteProvider
).
Source: (StackOverflow)
I'm getting around to learning JavaScript - really learning JavaScript. I come from a PHP background so some JavaScript concepts are still new to me, especially asynchronous programming. This question might have already been answered many times before but I have not been able to find an answer. It might be because I don't really even know how to ask the question other than by showing an example. So here it is:
When using the deferred package from npm, I see the following example:
delayedAdd(2, 3)(function (result) {
return result * result
})(function (result) {
console.log(result); // 25
});
They refer to this as chaining and it actually works as I'm currently using this code to check when a promise is resolved or is rejected. Even though they call it chaining, it reminds me of trailing closures like in Swift.
I don't really understand what type of chaining this is since we have a function invocation and then immediately after, an anonymous function enclosed in parentheses.
So I guess I have two questions.
- What pattern is this?
- How does it work? This may be a loaded question but I like to know how something works so when someone asks me about this I can give them a detailed explanation.
Here is the delayedAdd function:
var delayedAdd = delay(function (a, b) {
return a + b;
}, 100);
which uses the following function:
var delay = function (fn, timeout) {
return function () {
var def = deferred(), self = this, args = arguments;
setTimeout(function () {
var value;
try {
value = fn.apply(self, args));
} catch (e) {
def.reject(e);
return;
}
def.resolve(value);
}, timeout);
return def.promise;
};
};
Source: (StackOverflow)
I need to make a series of N ajax requests without locking the browser, and want to use the jquery deferred object to accomplish this.
Here is a simplified example with three requests, but my program may need to queue up over 100 (note that this is not the exact use case, the actual code does need to ensure the success of step (N-1) before executing the next step):
$(document).ready(function(){
var deferred = $.Deferred();
var countries = ["US", "CA", "MX"];
$.each(countries, function(index, country){
deferred.pipe(getData(country));
});
});
function getData(country){
var data = {
"country": country
};
console.log("Making request for [" + country + "]");
return $.ajax({
type: "POST",
url: "ajax.jsp",
data: data,
dataType: "JSON",
success: function(){
console.log("Successful request for [" + country + "]");
}
});
}
Here is what gets written into the console (all requests are made in parallel and the response time is directly proportional to the size of the data for each country as expected:
Making request for [US]
Making request for [CA]
Making request for [MX]
Successful request for [MX]
Successful request for [CA]
Successful request for [US]
How can I get the deferred object to queue these up for me? I've tried changing done to pipe but get the same result.
Here is the desired result:
Making request for [US]
Successful request for [US]
Making request for [CA]
Successful request for [CA]
Making request for [MX]
Successful request for [MX]
Edit:
I appreciate the suggestion to use an array to store request parameters, but the jquery deferred object has the ability to queue requests and I really want to learn how to use this feature to its full potential.
This is effectively what I'm trying to do:
when(request[0]).pipe(request[1]).pipe(request[2])... pipe(request[N]);
However, I want to assign the requests into the pipe one step at a time in order to effectively use the each traversal:
deferred.pipe(request[0]);
deferred.pipe(request[1]);
deferred.pipe(request[2]);
Source: (StackOverflow)
I've spent far too many hours searching for similar questions and trying solutions, so I hope someone has a solution.
Basically, I would like to be notified when a function a() has completed. The problem is that the function contains an ajax call and a loop that calls b(), which again contains an ajax call.
UPDATED WITH FIDDLE: http://jsfiddle.net/hsyj7/1/
Like so:
// called by main()
function a() {
return $.ajax("http://url1").pipe(function(data){
for (var i = 0; i < 2; i++) {
console.log('a called');
b();
}
});
}
// called by a()
function b() {
for (var i = 0; i < 2; i++) {
$.ajax("http://url2", function(data){
// do something
console.log('b called');
}
}
}
function main(){
$.when(a()).done(function(){
console.log('all completed');
});
}
What I would like to see then is, possibly with both calls to a() at the top:
a called
b called
b called
a called
b called
b called
all completed
Instead I get
a called
all completed
b called
b called
Or some variant thereof.
I am aware that the above code is missing defer functionality in both the loop and in b().
In some of the variants I have tried, the done() handler in main() is never called.
Any one know how to do this?
Source: (StackOverflow)
Let's create a simple Deferred object:
defer = $.Deferred( function ( defer ) {
setTimeout( defer.resolve, 3000 );
});
The above Deferred object will be in the "pending" state for 3 seconds, and then switch to the "resolved" state (at which point all the callbacks bound to it will be invoked).
Let's also retrieve the promise of that Deferred object:
promise = defer.promise();
Now, to add callbacks which are going to be invoked once the Deferred object is resolved, we can use .done()
or .then()
. However, we can invoke this method both on the Deferred object itself or its own promise object.
defer.then( handler );
or
promise.then( handler );
In both cases, the handler
function will be invoked (after 3 seconds in this case).
If we use $.when
, we can again pass the Deferred object itself or its promise object:
$.when( defer ).then( handler );
or
$.when( promise ).then( handler );
Again, there is no difference between the above two lines of code.
Live demo: http://jsfiddle.net/G6Ad6/
So, my question is since we can invoke .then()
, .done()
, etc. on the Deferred object itself and since we can pass that Deferred object into $.when()
, what's the point of .promise()
and retrieving the promise object? What's the purpose of the promise object? Why is there this redundancy in functionality?
Source: (StackOverflow)
I have three HTTP calls that need I need to make in a synchronous manner and how do I pass data from one call to the other?
function first()
{
ajax()
}
function second()
{
ajax()
}
function third()
{
ajax()
}
function main()
{
first().then(second).then(third)
}
I tried to use the deferred for the two functions and I came up with a partial solution. Can I extend it to be for three functions?
function first() {
var deferred = $.Deferred();
$.ajax({
"success": function (resp)
{
deferred.resolve(resp);
},
});
return deferred.promise();
}
function second(foo) {
$.ajax({
"success": function (resp)
{
},
"error": function (resp)
{
}
});
}
first().then(function(foo){second(foo)})
Source: (StackOverflow)
This should be a simple one.
I have a function that is called and I need to wait for all the async operations to complete.
what I want is something like this...
self.processSchema(data).done(function(results){ //do stuff});
The processSchema function loops using $.each and calls an async method.
var processSchema = function(data)
{
var def = new $.Deferred();
$.each(table, function()
{
//calls an async SQLitePlugin method
db.executeSql(sql, data, function(tx, results){
def.resolve(results);
}
}
return(def.promise());
}
This does not seem to work, I am new to $.Deferred so any guidance would be helpful
Source: (StackOverflow)
I have used promises in jQuery slightly before - but I am having trouble applying it to this scenario. I prefer to use the $.when() and $.done() methods to achieve this.
From what I understand I need to build a $.Deferred object which logs the requests and when those requests are finished - fire the callback. In my code below the callback is firing before the ajax requests and not after - maybe I just need some sleep
I know my code is incomplete I have been struggling to apply it with the addition of the for loop.
http://jsfiddle.net/whiteb0x/MBZEu/
var list = ['obj1', 'obj2', 'obj3', 'obj4', 'obj5'];
var callback = function() {
alert("done");
};
var requests = [];
var ajaxFunction = function(obj, successCallback, errorCallback) {
for(i = 0; i < list.length; i++) {
$.ajax({
url: 'url',
success: function() {
requests.push(this);
}
});
}
};
$.when($.ajax(), ajaxFunction).then(function(results){callback()});
Source: (StackOverflow)
I was in the shower and thought about something.
The deferred / promise pattern is to decrease callback hell, by allowing the developer to chain call functions, as mentioned here:
Parse.User.logIn("user", "pass").then(function(user) {
return query.find();
}).then(function(results) {
return results[0].save({ key: value });
}).then(function(result) {
// the object was saved.
});
From the top of my head - correct me if I am wrong - but it seems like using deferred / promises is an easy way to break the Law of Demeter?
The Law of Demeter states:
A method of an object may only call methods of:
- The object itself.
- An argument of the method.
- Any object created within the method.
- Any direct properties/fields of the object.
Each unit should have only limited knowledge about other units: only
units "closely" related to the current unit. Or: Each unit should only
talk to its friends; Don’t talk to strangers.
Any comments concerning this?
Update December 1 2013:
A summarized version of my question. The Promise framework is designed to simplify asynchronous coding and avoid "callback hell". One of the most beneficial features of Promise is that you can chain-call events by using .then()
, as seen in my example above.
Given all code/functions are now using Promise (like Benjamin Gruenbaum (author below) is currently doing), won't it open it up to make chain-calling functions really easy by going .then().then().then()
etc.
Writing code that chain-call functions after each other (.then().then().then()
) has to be a text-book example of how to break the Law of Demeter.
Hence my question; Does the Promise framework promote / open up / make it easier to abuse / break the Law of Demeter?
Source: (StackOverflow)
Lets say I want to process some tasks in the synchronous manner, so I have this function:
function executePromiseQueueSync(queue){
var seed = $.Deferred(),
finalPromise;
finalPromise = _.reduce(queue, function(memo, promise){
return memo.then(function(){
return promise.funct.apply(null, promise.argmnt);
});
}, seed.promise());
seed.resolve();
return finalPromise;
}
Now I can use it to process some files:
_.each(fileList, function(element, index, list){
_.each(element, function(el, idx, lst){
promisesQueue.push({funct: processFile, argmnt:[el, index + (len - fileList.length) ,len]});
});
});
Execute it and indicate a progress:
executePromiseQueueSync(promisesQueue).then(function(){
....
}, function(){
....
}).progress(function(msg, progress, name, index, status, desc){
console.log('progress');
});
Process function itself looks like this:
function processFile(file, index, size)
{
var dfd = new jQuery.Deferred();
if (file.name.match('(.*)\\.jpg'))
...
else if
...
else
$.when(processWrongFileType(file)).then(function(){
dfd.notify(...);
dfd.resolve();
});
return dfd.promise();
}
as you see there is nothing much to do when the file has a wrong type:
So sometimes I would like to execute synchronous code just like a promise:
function processWrongFileType(){
var dfd = new jQuery.Deferred();
dfd.resolve();
console.log("blah");
return dfd.promise();
}
The problem is if processWrongFileType will be executed, notify will not work.
If I change processWrongFileType to look like this:
function processWrongFileType()
{
var dfd = new jQuery.Deferred();
setTimeout(function(){dfd.resolve();},1);
return dfd.promise();
}
notify() will work. Is there any way to avoid setTimeout and still have notify() working with progress event?
Source: (StackOverflow)
I am have a problem understanding why rejections are not passed on through a promise chain and I am hoping someone will be able to help me understand why. To me, attaching functionality to a chain of promises implies an intent that I am depending on an original promise to be fulfilled. It's hard to explain, so let me show a code example of my problem first. (Note: this example is using Node and the deferred node module. I tested this with Dojo 1.8.3 and had the same results)
var d = require("deferred");
var d1 = d();
var promise1 = d1.promise.then(
function(wins) { console.log('promise1 resolved'); return wins;},
function(err) { console.log('promise1 rejected'); return err;});
var promise2 = promise1.then(
function(wins) { console.log('promise2 resolved'); return wins;},
function(err) { console.log('promise2 rejected'); return err;});
var promise3 = promise2.then(
function(wins) { console.log('promise3 resolved'); return wins;},
function(err) { console.log('promise3 rejected'); return err;});
d1.reject(new Error());
The results of running this operation is this output:
promise1 rejected
promise2 resolved
promise3 resolved
Okay, to me, this result doesn't make sense. By attaching to this promise chain, each then is implying the intent that it will be dependant upon the successful resolution of d1 and a result being passed down the chain. If the promise in promise1 doesn't receive the wins value, but instead gets an err value in its error handler, how is it possible for the next promise in the chain to have its success function called? There is no way it can pass on a meaningful value to the next promise because it didn't get a value itself.
A different way I can describe what I'm thinking is: There are three people, John, Ginger, and Bob. John owns a widget shop. Ginger comes into his shop and requests a bag of widgets of assorted colours. He doesn't have them in stock, so he sends in a request to his distributor to get them shipped to him. In the mean time, he gives Ginger a rain check stating he owes her the bag of widgets. Bob finds out Ginger is getting the widgets and requests that he get the blue widget when she's done with them. She agrees and gives him a note stating she will. Now, John's distributor can't find any widgets in their supply and the manufacturer doesn't make them any more, so they inform John, who in turn informs Ginger she can't get the widgets. How is Bob able to get a blue widget from Ginger when didn't get any herself?
A third more realistic perspective I have on this issue is this. Say I have two values I want updated to a database. One is dependant on the id of the other, but I can't get the id until I have already inserted it into a database and obtained the result. On top of that, the first insert is dependant on a query from the database. The database calls return promises that I use to chain the two calls into a sequence.
var promise = db.query({parent_id: value});
promise.then(function(query_result) {
var first_value = {
parent_id: query_result[0].parent_id
}
var promise = db.put(first_value);
promise.then(function(first_value_result) {
var second_value = {
reference_to_first_value_id: first_value_result.id
}
var promise = db.put(second_value);
promise.then(function(second_value_result) {
values_successfully_entered();
}, function(err) { return err });
}, function(err) { return err });
}, function(err) { return err });
Now, in this situation, if the db.query failed, it would call the err function of the first then. But then it would call the success function of the next promise. While that promise is expecting the results of the first value, it would instead get the error message from its error handler function.
So, my question is, why would I have an error handing function if I have to test for errors in my success function?
Sorry for the length of this. I just didn't know how to explain it another way.
UPDATE and correction
(Note: I removed a response I had once made to some comments. So if anyone commented on my response, their comments might seem out of context now that I removed it. Sorry for this, I am trying to keep this as short as possible.)
Thank you everybody who replied. I would like to first apologize to everybody for writing out my question so poorly, especially my pseudo code. I was a little too aggressive in trying to keep it short.
Thanks to Bergi's response, I think I found the error in my logic. I think I might have overlooked another issue that was causing the problem I was having. This is possibly causing the promise chain work differently than I thought it should. I am still testing different elements of my code, so I can't even form a proper question to see what I'm doing wrong yet. I did want to update you all though and thank you for your help.
Source: (StackOverflow)
I feel it would be useful to have a naming convention for JavaScript variables which hold a promise. I don't generally like or advocate naming conventions beyond programming language standards, but in the style of programming where promises are passed around as function arguments it's often hard to tell at a glance whether a variable holds a promise or the "real thing".
I've personally used promiseOfFoo
and pFoo
, but I find the former a bit verbose, and the latter gives me flashbacks from Hungarian.
Is there a commonly used convention?
Source: (StackOverflow)