So I'm doing a an ajax call in this function somewhat like this:
function getCount() {
$.get("/People/getCount", function (data) {
if (data && data != "") {
// lots of code in here
}
What I'm doing in another function is making a second call like this:
function worldPeople() {
return $.get("/People/getCount", function (data) {
if (data != 0) {
var target = $("#worldNumbers").find("span");
target.html(data.length).digits();
}
})
}
So I really would like to avoid making that second call. Is there any good way in avoiding that? Maybe do some chaining or such, reusing the callback from the first one? I've heard that its bad practice to do several calls.
Regards
Would like to thank all who answered. In the end did not use any of the solutions, I solved it in another way. I'm sure most of the examples you gave me were really good. Do not know how to do with accepting answers. Accept all or none?! Thanks!
You could create a simple data store:
App.store = function () {
this.people = null;
this.count
loadPeople = function () {
if(this.people === null) {
$.get("/People/getCount", function (data) {
if (data != 0) {
this.count = (data.length).digits();
this.people = data;
}
}
};
}
What about store count of peoples in hidden field? And than check this field before sending request.
You can achieve this by handling your Ajax requests using some sort of cache. I use a cache that saves the information retrieved based on the url it called. If another function sets off the same request the cache returns the alraedy fetched data.
What you do need to do as well though is check if the data is outdated so you can refetch it if necessary.
Well, you can just send the function pointer to the function that executes $.get
basically you would then do this:
function worldPeople() {
getCountFromServer(function(data){
//do sth with data
});
}
function getCount() {
getCountFromServer(function(data){
//do sth with data
});
}
function getCountFromServer(callback) {
return $.get("/People/getCount", function (data) {
if (data)
callback(data);
});
}
I generally use a caching module pattern for this kind of thing:
// create a quick singleton to store cached data
var People = (function() {
// private variable to act as cache
var count;
// function to get cached data
// note: You have to assume it's always asynchronous
function getCount(callback) {
// have we loaded the data yet?
if (count===undefined) {
// cache miss: load the data, store it, do the callback
$.get("/People/getCount", function (data) {
count = data;
callback(data);
}
} else {
// cache hit - no need to reload
callback(count);
}
}
// provide access to the getter function
return {
getCount: getCount
};
}());
The first time you hit the cache, it'll load from the server; the second time it will load from the private variable.
// will load the data asynchronously
People.getCount(function(count) {
alert("First hit: " + count);
});
// will use the cached data
People.getCount(function(count) {
alert("Second hit: " + count);
});
Depending on the complexity you want to support, you could add additional features like expiring the cache after a particular interval, caching multiple calls (potentially keyed to the AJAX URL), etc. I like to keep the API simple and not reference the AJAX URLs - that way your cache acts like an abstracted service layer, and you can create other cache implementation to work with different data sources - useful for things like stubbing out data before you've implemented your server-side AJAX handlers.
Related
React/Redux n00b here :) - working with a crappy API that doesn't correctly return error codes (returns 200 even when end point is down), therefore is messing up my Ajax calls. Owner of the API will not able to correct this soon enough, so I have to work around it for now.
I'm currently checking each success with something like this (using lodash):
success: function(data) {
// check if error is REALLY an error
if (_.isUndefined(data.error) || _.isNull(data.error)) {
if (data.id) data.sessionId = data.id;
if (data.alias) data.alias = data.alias;
resolve(data || {});
} else {
reject(data); // this is an error
}
}
I want to move this into it's own function so that I can use it with any action that performs an Ajax call, but I'm not sure where to include this.
Should this type of function map to state (hence, treat it like an action and build a reducer) or should this be something generic outside of Redux and throw in main.js for example?
You can dispatch different actions depending on if the promise was resolved or not. The simplest way would be something like this:
function onSuccess(data) {
return {
type: "FETCH_THING_SUCCESS",
thing: data
};
}
function onError(error) {
return {
type: "FETCH_THING_ERROR",
error: error
};
}
function fetchThing(dispatch, id) {
// the ajax call that returns the promise
fetcher(id)
.then(function(data){
dispatch(onSuccess(data));
})
.catch(function(error) {
dispatch(onError(error));
});
}
Heres some more documentation how to do this kind of thing...
I have an app which wants to get info about every marker on a map.
Each marker has a class, such as "car" or "pedestrian".
The app makes (via jQuery) a getJSON call to "http://myserver/info/".
However, since multiple markers may have the same class, the server could end up getting hit with many requests.
Accordingly, I'd like to pool requests which occur within a specified time frame (maybe 5 seconds or so) so that only one request is made, but each calling instance of getJSON is unaware of it.
My thought is to wrap getJSON in another function which stores the URLS in a hashmap/dictionary and stores up promises for each requester. When data is returned, the promises are fulfilled.
I ask, is there a standard way of doing this (debouncing an AJAX request, as it were)?
I created something (in 25 minutes ^^) that might help you; it's a Timeout manager:
var requestsPool = {
requests: {}, //list of urls
timeout: 5000, //In milliseconds
add: function(url) {
if(requestsPool.exists(url)) return false; //check if url is already present in the pool
requestsPool.requests[url] = setTimeout(function(u) {
requestsPool.remove(u);
}.bind(this, url), requestsPool.timeout); //Defining the timeout
return true;
},
exists: function(url) {
return requestsPool.requests[url]; //Return the Timeout ID if present or undefined
},
remove: function(url) {
return delete requestsPool.requests[url]; //return true almost always #link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete
},
cancel: function(url) {
clearTimeout(requestsPool.requests[url]); //cancel the timeout
return requestsPool.remove(url); //remove the url form the pool
}
}
$(anchor).click(function() {
if(requestsPool.exists(anchor.href)) {
// If cooldown is present
} else {
$.getJSON(anchor.href, function(data) {
requestsPool.add(anchor.href);
});
}
})
My thought is to wrap getJSON in another function which stores the URLS in a hashmap/dictionary and stores up promises for each requester
Yes, that's a good idea. It might look like this:
var debouncedGet = (function() {
var pool = {};
return function get(url) {
if (!pool[url]) {
pool[url] = $.getJSON(url);
setTimeout(function() {
pool[url] = null;
}, 5000); // you might want to move this into a `pool[url].always(…)` callback
// so the timer starts when the request returned
}
return pool[url];
};
}());
Here's my bid:
(function(window,$,undefined){
'use strict';
var cache = {},
timeout = 5e3;
// Use like traditional $.getJSON
$.getJSON = function(url,data,callback){
if ($.isFunction(data)){
callback = data;
data = undefined;
}
// Establish a cache key so we can re-reference existing
// requests to subsequent ones (within the timeout window).
var cacheKey = url;
if (cache[cacheKey]){
// This is an existing request; Simple add the callback
// onto the promise and return it.
return cache[cacheKey].done(callback);
} else {
// This is a new request. Build up a new request,
// attach the callback to the promise, and also add
// a couple cleanup methods for disposing the cache
// when appropriate.
cache[cacheKey] = $.ajax($.extend({
url: url,
type: 'get',
dataType: 'json',
data: data,
}, $.isPlainObject(url) && url))
.done(callback)
.always(function(){
delete cache[cacheKey];
});
setTimeout(function(){
// TODO: Probbaly want to store a reference to
// this timeout and clear it in the .always (to
// avoid race condition between .always firing
// and new request coming in but not returning yet)
cache[cacheKey] && delete cache[cacheKey];
}, timeout);
return cache[cacheKey];
}
};
})(window,jQuery);
And, FWIW, a jsFiddle: http://jsfiddle.net/ajtbdxt7/
Please forgive me if this is a stupid question. I have been trying for hours and my brain have just stopped working.
I have such system that consists of three AJAX calls. Server response of first call usually is a 200 Success; but second and third queries are fragile because they are image uploading, and on the server side, I have so much validation rules that client's images mostly fail.
window.AjaxCall = function () {
// to pass to $.ajax call later
this.args = arguments;
// xhr status
this.status = null;
// xhr results (jqXHR object and response)
this.xhrResponse = {};
this.dfr = new $.Deferred();
// to provide an easier interface
this.done = this.dfr.done;
this.fail = this.dfr.fail;
this.then = this.dfr.then;
};
AjaxCall.prototype.resetDfr = function () {
this.dfr = new $.Deferred();
};
AjaxCall.prototype.resolve = function () {
this.dfr.resolve(
this.xhrResponse.result,
this.xhrResponse.jqXHR
);
this.resetDfr();
};
AjaxCall.prototype.reject = function () {
this.dfr.reject(
this.xhrResponse.jqXHR
);
this.resetDfr();
};
AjaxCall.prototype.query = function () {
var _this = this;
// if query hasn't run yet, or didn't return success, run it again
if (_this.status != 'OK') {
$.ajax.apply(_this, _this.args)
.done(function (result, textStatus, jqXHR) {
_this.xhrResponse.result = result;
_this.xhrResponse.jqXHR = jqXHR;
_this.resolve();
})
.fail(function (jqXHR) {
_this.xhrResponse.jqXHR = jqXHR;
_this.reject();
})
.always(function (a, b, c) {
var statusCode = (typeof c !== 'string'
? c
: a).status;
if (statusCode == 200) {
_this.status = 'OK';
}
});
}
// if query has been run successfully before, just skip to next
else {
_this.resolve();
}
return _this.dfr.promise();
};
AjaxCall class is as provided above, and I make the three consecutive calls like this:
var First = new AjaxCall('/'),
Second = new AjaxCall('/asd'),
Third = new AjaxCall('/qqq');
First.then(function () {
console.log('#1 done');
}, function() {
console.error('#1 fail');
});
Second.then(function () {
console.log('#2 done');
}, function() {
console.error('#2 fail');
});
Third.then(function () {
console.log('#3 done');
}, function() {
console.error('#3 fail');
});
var toRun = function () {
First.query()
.then(function () {
return Second.query();
})
.then(function () {
return Third.query()
});
};
$('button').click(function () {
toRun();
});
Those code are in a testing environment. And by testing environment, I mean a simple HTML page and basic server support for debugging.
Home page (/) always returns 200 Success.
/asd returns 404 Not Found for the first 3 times and 200 Success once as a pattern (i.e. three 404s -> one 200 -> three 404s -> one 200 -> three 404s -> ... ).
/qqq returns 404 Not Found all the time.
When I click the only button on the page, first query returns success and second fails as expected. When I click the button second time, first query skips because it was successful last time and second fails again, also as expected.
The problem here is:
before I used the resetDfr method because the dfr is alreay resolved or rejected, it doesn't react to resolve and reject methods anymore.
When I call the resetDfr method in the way I show in the example, dfr is able to get resolved or rejected again, but the callbacks of the old dfr are not binded with the new dfr object and I couldn't find a way to clone the old callbacks into the new dfr.
What would be your suggestion to accomplish what I'm trying to do here?
Promises represent a single value bound by time. You can't conceptually "reuse" a deferred or reset it - once it transitions it sticks. There are constructs that generalize promises to multiple values (like observables) but those are more complicated in this case - it's probably better to just use one deferred per request.
jQuery's AJAX already provides a promise interface. Your code is mostly redundant - you can and should consider using the existent tooling.
Let's look at $.get:
It already returns a promise so you don't need to create your own deferred.
It already uses the browser cache, unless your server prohibits HTTP caching or the browser refuses it only one request will be made to the server after a correct response arrived (assuming you did not explicitly pass {cache: false} to its parameters.
If making post requests you can use $.post or more generally $.ajax for arbitrary options.
This is how your code would roughly look like:
$("button").click(function(){
var first = $.get("/");
var second = first.then(function(){
return $.get("/asd");
});
var third = second.then(function(){
return $.get("/qqq");
});
});
The reason I put them in variables is so that you will be able to unwrap the result yourself later by doing first.then etc. It's quite possible to do this in a single chain too (but you lose access to previous values if you don't explicitly save them.
For the record - it wasn't a stupid question at all :)
I'm writing a Chrome extension with the socket api(though this doc is out of date, the latest version of the api is here), and I found that the code is really hard to organize:
All the methods are under the namespace chrome.experimental.socket, I would just use socket below for simplicity.
socket.create("tcp", {}, function(socketInfo){
var socketId = socketInfo.socketId;
socket.connect(socketId, IP, PORT, function(result){
if(!result) throw "Connect Error";
socket.write(socketId, data, function(writeInfo){
if(writeInfo.bytesWritten < 0) throw "Send Data Error";
socket.read(socketId, function(readInfo){
if(readInfo.resultCode < 0) throw "Read Error";
var data = readInfo.data; // play with the data
// then send the next request
socket.write(socketId, data, function(writeInfo){
socket.read(socketId, function(readInfo){
// ............
});
});
});
})
});
})
because both socket.write and socket.read are asynchronous, I have to nest the callbacks to make sure that the next request is send after the previous request got the correct response.
it's really hard to manage these nested functions, how could I improve it?
UPDATE
I'd like to have a method send which I can use as:
send(socketId, data, function(response){
// play with response
});
// block here until the previous send get the response
send(socketId, data, function(response){
// play with response
});
How about (something like) this?
var MySocket = {
obj: null,
data: null,
start: function() { ... some code initializing obj data, ending with this.create() call },
create: function() { ... some code initializing obj data, ending with this.connect() call },
connect: function() { ... some connection code, ending with this.write() call },
write: function() { ... some writing code that updates this.data, ending with this.read() call },
read: function() { ... you probably get the idea at this point )) ... },
};
This object could be used with MySocket.start() or something. The idea is to encapsulate all data (and nested calls) within the single (yet more-o-less globally usable) object.
Or even more, one can create two objects: one purely for writing purposes, and another for purely reading, each operating with its own data, then wrap them (and their inter-calls, so to speak) into a single SocketManager object.
Consider using an asynchronous continuation passing style, where functions end with a SetInterval call with the function they were passed. Then we construct a function that entwines two functions to call each other using this mechanism. The guts of it would be like this:
var handle;
// pairs two functions
function pair(firstfunc, secondfunc, startarg) {
var callbackToFirst = function(valuetofill) {
handle = setInterval(firstfunc(valuetofill,callbackToSecond));
};
var callbackToSecond = function(valuetofill) {
handle = setInterval(secondfunc(valuetofill,callbackToFirst));
};
callbackToFirst(startarg);
}
What we are doing here is constructing a pair of mutually-calling callbacks which take a single argument, which each contain references to the two inter-calling functions. We then kick off the process by calling the first callback.
Construct the pair for an example pair of read and write functions (assuming you've set the socketId in the enclosing object definition):
// starts read/write pair, sets internal variable 'handle' to
// interval handle for control
function startReadWrite(initialarg, myDataFunc) {
var readcall = function(value, func) {
readSocket(getData(myDataFunc(func)));
};
var writecall = function(value, func) {
writeSocket(checkBytesWritten(func));
};
handle = pair(readcall, writecall, initialarg);
}
The rest of the object is like this:
function myIO() {
var socketInfo, socketId, handle;
function create(func) {
socket.create('tcp',{},function(thisSocketInfo) {
socketInfo = thisSocketInfo;
}
setInterval(func(this),0);
}
function connect(IP, PORT, func) {
socket.connect(p_socketId, IP, PORT, function() {
if(!result) throw "Connect Error";
setInterval(func(result),0);
});
}
function readSocket(func) {
socket.read(p_socketId, function(readInfo){
setInterval(func(readInfo),0);
});
}
function writeSocket(data, func) {
socket.write(p_socketId, data, function(writeInfo){
setInterval(func(writeInfo),0)
});
}
function checkBytesWritten(writeInfo, func) {
if(writeInfo.bytesWritten < 0) throw "Send Data Error";
setInterval(func(writeInfo),0);
}
function getData(readInfo, func) {
if(readInfo.resultCode < 0) throw "Read Error";
var data = readInfo.data;
setInterval(func(data),0);
}
//** pair and startReadWrite go here **//
}
Finally the call to set the whole thing going:
var myIOobj = new myIO();
myIOobj.create(startReadWrite(myDataFunc));
Notes:
This is meant to demonstrate a style, not be ready code! Don't just copy and paste it.
No, I haven't tested this; I do javascript but not Chrome API stuff yet. I'm focussing on the callback mechanisms etc.
Be careful with the different classes of callback; single argument callbacks (like the read and write callbacks) which take a single value (as presumably defined by the API), and 2 argument callbacks (like most of the methods) which take an argument and a function to call at the end.
The getData method takes a callback and passes data to it; this callback (myDataFunc) is the function that actually gets to use the data. It needs to take a callback as a second argument and call it synchronously or asynchronously.
TLDR: Consider using asynchronous calls to avoid the nesting. I've given a vague example of a mechanism to have two functions call each other continuously using this style as seems to be needed.
Although I call it asynchonous, the setInterval calls will execute serially, but the key is that the stack is cleared after the parent call is done, rather than adding endless layers with nesting.
my code creates two ajax call at the same time (i assume the parallelism would be more efficient). I want to load a table if both calls succeed. What's the proper way of doing this?
var succeeded = {};
function callBackOne(){
succeeded.one = true;
// your other stuff
if (succeeded.two) { bothHaveSucceeded());
}
function callBackTwo(){
succeeded.two = true;
// your other stuff
if (succeeded.one) { bothHaveSucceeded());
}
I'd use a delayed task personally:
var success = {
one: false,
two: false
};
// Task
var task = new Ext.util.DelayedTask(function(){
// Check for success
if (success.one && success.two) {
// Callback
doCallback();
} else {
task.delay(500);
}
});
task.delay(500);
// First
Ext.Ajax.request({
...
success: function() {
success.one = true;
}
...
});
// Second
Ext.Ajax.request({
...
success: function() {
success.two = true;
}
...
});
The task acts like a thread and will check on the status of the requests and sleep for every 500ms until they both complete.
Old question, but well, as I stumbled upon it...
I'd use the excellent async library by Caolan, particularly here you'll want to use async.parallel.
The examples written on the GitHub doc are worth a read.
https://github.com/caolan/async#parallel
Share an integer variable that each callback checks:
// count variable
var numReturns = 0;
// same call back used for each Ajax request:
function callback() {
numReturns++;
if (numReturns === 2) {
progress();
}
}
If you need different callbacks, have each callback fire an event which does the same thing.