Hi everyone I am trying to use ajax inside a loop using promise, but my second ajax call inside the loop don't way for the ajax request and continue the execution.
This is my code:
var general = [];
var all_info =[];
var usuario =[];
var resultPromise = getProjects(); // Promise for a response.
resultPromise.then(function(all_projects) {
return $.when.apply($, all_projects.map(function (current_project, index){
var items = {};
items.name = current_project.key;
items.children = [{"total_cpu": current_project.cpuhour_tot, "num_jobs" : current_project.num_jobs }];
return addUsers(current_project.key)
.then(function(item_user) {
info_user = {};
info_user.name = item_user.key;
info_user.children = [{"total_cpu" : item_user.cpuhour_tot, "num_jobs": item_user.num_jobs }];
all_info.push(info_user);
});
items.children.push(all_info);
general.push(items)
}));
})
.then(function() {
console.log("complete", general);
})
.fail(function(jqxhr, textStatus, errorThrown) {
console.log(errorThrown);
})
when I return from this line return addUsers... I need to include the all_info values to items and before to execute other loop to all_projects I have to do that general.push(items)
but it is impossible to access to items.
What I am missing?
Thanks in advance!
Substitute .map() for .forEach() use $.when(), Function.prototype.apply(). usuario is an array; .push() value to the array.
resultPromise.then(function(all_projects) {
return $.when.apply($, all_projects.map(function (current_project, index){
var items = {};
items.name = current_project.key;
items.children = [{"total_cpu": current_project.cpuhour_tot, "num_jobs" : current_project.num_jobs }];
return addUsers(current_project.key)
.then(function(value) {
console.log(value)
usuario.push(value);
// use value here before continues;
// do stuff with `value` or `usuario` here
});
}));
})
.then(function() {
console.log("complete", usuario)
})
.fail(function(jqxhr, textStatus, errorThrown) {
console.log(errorThrown)
})
Reading about the asynchronous and single threaded nature of javascript would help you understand what happens here.
Essentially the following instruction:
resultPromise.then(function(value) {
usuario = value;
// use value here before continues;
console.log("first");
});
Is asking "Execute the callback function at some point in the future when the promise is resolved and execution stack is cleared". The callback function doesn't run in place, and actually won't run until after the current execution thread completes.
I have a javascript code which have to request the database (ajax). But I discovered that the inserts were wrong but with the right sql request. So I added an alert on which ajax request to know when the code is executed.
Here is the code :
$.post("/kohana-v3.3.5/ajax/update_simulation", {
id_simulation: id_simulation,
nom_simulation: nom_simulation,
sol_simulation: sol_simulation,
station_simulation: station_simulation,
iteration_simulation: iteration_simulation,
scenario_simulation: scenario_simulation
}
, function (result) {
console.log(result);
alert('update');
});
$.post("/kohana-v3.3.5/ajax/delete_pousses", {id_simulation: id_simulation}, function (result) {
console.log(result);
alert('delete');
});
$(this).prev('div').find('table .formRows').each(function (i) {
alert('here');
if (cpt % 2 == 1) {
//interculture
var $tds = $(this).find('td option:selected'),
culture = $tds.eq(0).val(),
date = $tds.eq(1).text();
itk = null;
} else {
//culture
var $tds = $(this).find('td option:selected'),
culture = $tds.eq(0).val(),
itk = $tds.eq(1).val();
date = null;
}
$.post("/kohana-v3.3.5/ajax/insert_pousses", {
id_simulation: id_simulation,
culture: culture,
date: date,
itk: itk,
rang: cpt
}, function (result) {
console.log(result);
alert('insert');
}); //Fin du post
cpt++;
}); //Fin du each
Each time I run that code, the order of the alert is always different ! Sometimes "insert update delete", sometimes "update, delete insert" ...
And it's a problem because if the delete is the last one, the insert will be removed. So, is it a normal way ? How should I resolve it ?
javascript can be executed asynchronously - and that's the reason why your ajax requests are not always executed in the same order. You can set them asnyc false (like here jQuery: Performing synchronous AJAX requests) or make something like promises (https://api.jquery.com/promise/) to wait for the ajax call to be finished.
greetings
AJAX requests are asynchronous, so you cannot guarantee an order if you trigger them as siblings like this.
In order to guarantee a fixed order, you need to make the subsequent call from the success block of its predecessor. Something like this:
$.post('/ajax/method1', { params: params },
function(result) {
$.post('/ajax/method2', { params: params },
function(result) {
$.post('/ajax/method3', { params: params },
function(result) {
});
});
});
You can use .promise to "observe when all actions of a certain type bound to the collection, queued or not, have finished."
https://api.jquery.com/promise/
Example Function
function testFunction() {
var deferred = $.Deferred();
$.ajax({
type: "POST",
url: "",
success: function (data) {
deferred.resolve(data);
}
});
return deferred.promise();
}
Calling Function
function CallingFunction()
{
var promise = testFunction();
promise.then(function (data) {
//do bits / call next funtion
}
}
Update
This may also help you out:
"Register a handler to be called when all Ajax requests have completed."
https://api.jquery.com/ajaxStop/
$(document).ajaxStop(function () {
});
Final note:
As of jQuery 1.8, the use of async: false is deprecated, use with $.Deferred.
you need to call post ajax method after by the success of previous one.
like:
$.post("/kohana-v3.3.5/ajax/update_simulation", {
id_simulation: id_simulation,
nom_simulation: nom_simulation,
sol_simulation: sol_simulation,
station_simulation: station_simulation,
iteration_simulation: iteration_simulation,
scenario_simulation: scenario_simulation
}
, function (result) {
console.log(result);
alert('update');
dleteajax();
});
function dleteajax()
{
$.post("/kohana-v3.3.5/ajax/delete_pousses", {id_simulation: id_simulation}, function (result) {
console.log(result);
alert('delete');
});
}
I am facing the following synchronization issue. I wouldn't be surprised if it has a simple solution/workaround. The BuildMenu() function is called from another block of code and it calls the CreateMenuData() which makes a request to a service which return some data. The problem is that since it is an async call to the service when the data variable is being used it is undefined. I have provided the js log that also shows my point.
BuildMenu: function () {
console.log("before call");
var data=this.CreateMenuData();
console.log("after call");
//Doing more stuff with data that fail.
}
CreateMenuData: function () {
console.log("func starts");
data = [];
dojo.forEach(config.layerlist, function (collection, colindex) {
var layersRequest = esriRequest({
url: collection.url,
handleAs: "json",
});
layersRequest.then(
function (response) {
dojo.forEach(response.records, function (value, key) {
console.log(key);
data.push(key);
});
}, function (error) {
});
});
console.log("func ends");
return data;
}
Console log writes:
before call
func starts
func ends
after call
0
1
2
3
4
FYI: using anything "dojo." is deprecated. Make sure you are pulling all the modules you need in "require".
Ken has pointed you the right direction, go through the link and get familiarized with the asynchronous requests.
However, I'd like to point out that you are not handling only one async request, but potentionally there might be more of them of which you are trying to fill the "data" with. To make sure you handle the results only when all of the requests are finished, you should use "dojo/promise/all".
CreateMenuData: function (callback) {
console.log("func starts");
requests = [];
data = [];
var scope = this;
require(["dojo/_base/lang", "dojo/base/array", "dojo/promise/all"], function(lang, array, all){
array.forEach(config.layerlist, function (collection, colindex) {
var promise = esriRequest({
url: collection.url,
handleAs: "json",
});
requests.push(promise);
});
// Now use the dojo/promise/all object
all(requests).then(function(responses){
// Check for all the responses and add whatever you need to the data object.
...
// once it's all done, apply the callback. watch the scope!
if (typeof callback == "function")
callback.apply(scope, data);
});
});
}
so now you have that method ready, call it
BuildMenu: function () {
console.log("before call");
var dataCallback = function(data){
// do whatever you need to do with the data or call other function that handles them.
}
this.CreateMenuData(dataCallback);
}
I am trying to make multiple ajax requests and then display some content only after all ajax requests have been made. I know I should use jQuery promises but I'm not entirely sure how they work.
Here is my code:
//make first ajax request
$.ajax({
url: 'http://api.com',
success: function(result) {
var promises = [];
//for each result
for(var i = 0; i < result.length; i++) {
//make another ajax request using
//some of the returned data and
//define it as a promise
var promise = $.ajax({
url: 'http://api.com¶m='+result.paramVal,
success: function(result) {
return result;
}
});
//push promise into array
promises.push(promise);
}
//when each promise in the promises array is complete
$.when.apply($, promises).then(function() {
console.log(promises);
});
}
});
This seems to be working, but to better organize this code, I want to put all of this code into an object and then abstract out the subsequent ajax call into it's own method. My code looks like this:
var myObject = {
firstRequest: function() {
$.ajax({
url: 'http://api.com',
success: function(result) {
var promises = [];
for(var i = 0; i < result.length; i++) {
var promise = myObject.secondRequest(result.param);
promises.push(promise);
}
$.when.apply($, promises).then(function() {
myObject.displayContent(promises));
});
}
});
},
secondRequest: function(paramVal) {
$.ajax({
url: 'http://api.com¶m='+result.paramVal,
success: function(result) {
return result;
}
});
},
displayContent: function(promises) {
console.log(promises);
}
};
In this example, after running myObject.displayContent, each array item in promises is undefined. I think it's because myObject.secondRequest isn't actually a promise itself (the ajax request inside this function is the actual promise). How can I make this arrangement work?
UPDATE
Adding return to my ajax promise works but I am unable to access responseJSON in the ajax objects that are returned.
secondRequest: function(paramVal) {
return $.ajax({
url: 'http://api.com¶m='+result.paramVal,
success: function(result) {
return result;
}
});
},
Here is an image of one of the objects that is returned from my $.when.then() callback. I am able to access the readyState property, but not the responseJSON property.
You have to pass a function to .then, but you are immediately executing myObject.displayContent. It should be:
$.when.apply($, promises).then(function() {
myObject.displayContent(promises)
});
If you don't actually need access to the promises itself, pass the function directly:
$.when.apply($, promises).then(myObject.displayContent);
// or with `$.proxy` if you need `this` to refer to the object
$.when.apply($, promises).then($.proxy(myObject, 'displayContent'));
You also have to return the promise from your secondRequest function:
secondRequest: function(paramVal) {
return $.ajax(...);
}
Otherwise promise will be undefined in
var promise = myObject.secondRequest(result.param);
I'd like to update a page based upon the results of multiple ajax/json requests. Using jQuery, I can "chain" the callbacks, like this very simple stripped down example:
$.getJSON("/values/1", function(data) {
// data = {value: 1}
var value_1 = data.value;
$.getJSON("/values/2", function(data) {
// data = {value: 42}
var value_2 = data.value;
var sum = value_1 + value_2;
$('#mynode').html(sum);
});
});
However, this results in the requests being made serially. I'd much rather a way to make the requests in parallel, and perform the page update after all are complete. Is there any way to do this?
jQuery $.when() and $.done() are exactly what you need:
$.when($.ajax("/page1.php"), $.ajax("/page2.php"))
.then(myFunc, myFailure);
Try this solution, which can support any specific number of parallel queries:
var done = 4; // number of total requests
var sum = 0;
/* Normal loops don't create a new scope */
$([1,2,3,4,5]).each(function() {
var number = this;
$.getJSON("/values/" + number, function(data) {
sum += data.value;
done -= 1;
if(done == 0) $("#mynode").html(sum);
});
});
Run multiple AJAX requests in parallel
When working with APIs, you sometimes need to issue multiple AJAX requests to different endpoints. Instead of waiting for one request to complete before issuing the next, you can speed things up with jQuery by requesting the data in parallel, by using jQuery's $.when() function:
JS
$.when($.get('1.json'), $.get('2.json')).then(function(r1, r2){
console.log(r1[0].message + " " + r2[0].message);
});
The callback function is executed when both of these GET requests finish successfully. $.when() takes the promises returned by two $.get() calls, and constructs a new promise object. The r1 and r2 arguments of the callback are arrays, whose first elements contain the server responses.
Here's my attempt at directly addressing your question
Basically, you just build up and AJAX call stack, execute them all, and a provided function is called upon completion of all the events - the provided argument being an array of the results from all the supplied ajax requests.
Clearly this is early code - you could get more elaborate with this in terms of the flexibility.
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
var ParallelAjaxExecuter = function( onComplete )
{
this.requests = [];
this.results = [];
this.onComplete = onComplete;
}
ParallelAjaxExecuter.prototype.addRequest = function( method, url, data, format )
{
this.requests.push( {
"method" : method
, "url" : url
, "data" : data
, "format" : format
, "completed" : false
} )
}
ParallelAjaxExecuter.prototype.dispatchAll = function()
{
var self = this;
$.each( self.requests, function( i, request )
{
request.method( request.url, request.data, function( r )
{
return function( data )
{
console.log
r.completed = true;
self.results.push( data );
self.checkAndComplete();
}
}( request ) )
} )
}
ParallelAjaxExecuter.prototype.allRequestsCompleted = function()
{
var i = 0;
while ( request = this.requests[i++] )
{
if ( request.completed === false )
{
return false;
}
}
return true;
},
ParallelAjaxExecuter.prototype.checkAndComplete = function()
{
if ( this.allRequestsCompleted() )
{
this.onComplete( this.results );
}
}
var pe = new ParallelAjaxExecuter( function( results )
{
alert( eval( results.join( '+' ) ) );
} );
pe.addRequest( $.get, 'test.php', {n:1}, 'text' );
pe.addRequest( $.get, 'test.php', {n:2}, 'text' );
pe.addRequest( $.get, 'test.php', {n:3}, 'text' );
pe.addRequest( $.get, 'test.php', {n:4}, 'text' );
pe.dispatchAll();
</script>
here's test.php
<?php
echo pow( $_GET['n'], 2 );
?>
Update: Per the answer given by Yair Leviel, this answer is obsolete. Use a promise library, like jQuery.when() or Q.js.
I created a general purpose solution as a jQuery extension. Could use some fine tuning to make it more general, but it suited my needs. The advantage of this technique over the others in this posting as of the time of this writing was that any type of asynchronous processing with a callback can be used.
Note: I'd use Rx extensions for JavaScript instead of this if I thought my client would be okay with taking a dependency on yet-another-third-party-library :)
// jQuery extension for running multiple async methods in parallel
// and getting a callback with all results when all of them have completed.
//
// Each worker is a function that takes a callback as its only argument, and
// fires up an async process that calls this callback with its result.
//
// Example:
// $.parallel(
// function (callback) { $.get("form.htm", {}, callback, "html"); },
// function (callback) { $.post("data.aspx", {}, callback, "json"); },
// function (formHtml, dataJson) {
// // Handle success; each argument to this function is
// // the result of correlating ajax call above.
// }
// );
(function ($) {
$.parallel = function (anyNumberOfWorkers, allDoneCallback) {
var workers = [];
var workersCompleteCallback = null;
// To support any number of workers, use "arguments" variable to
// access function arguments rather than the names above.
var lastArgIndex = arguments.length - 1;
$.each(arguments, function (index) {
if (index == lastArgIndex) {
workersCompleteCallback = this;
} else {
workers.push({ fn: this, done: false, result: null });
}
});
// Short circuit this edge case
if (workers.length == 0) {
workersCompleteCallback();
return;
}
// Fire off each worker process, asking it to report back to onWorkerDone.
$.each(workers, function (workerIndex) {
var worker = this;
var callback = function () { onWorkerDone(worker, arguments); };
worker.fn(callback);
});
// Store results and update status as each item completes.
// The [0] on workerResultS below assumes the client only needs the first parameter
// passed into the return callback. This simplifies the handling in allDoneCallback,
// but may need to be removed if you need access to all parameters of the result.
// For example, $.post calls back with success(data, textStatus, XMLHttpRequest). If
// you need textStatus or XMLHttpRequest then pull off the [0] below.
function onWorkerDone(worker, workerResult) {
worker.done = true;
worker.result = workerResult[0]; // this is the [0] ref'd above.
var allResults = [];
for (var i = 0; i < workers.length; i++) {
if (!workers[i].done) return;
else allResults.push(workers[i].result);
}
workersCompleteCallback.apply(this, allResults);
}
};
})(jQuery);
UPDATE And another two years later, this looks insane because the accepted answer has changed to something much better! (Though still not as good as Yair Leviel's answer using jQuery's when)
18 months later, I just hit something similar. I have a refresh button, and I want the old content to fadeOut and then the new content to fadeIn. But I also need to get the new content. The fadeOut and the get are asynchronous, but it would be a waste of time to run them serially.
What I do is really the same as the accepted answer, except in the form of a reusable function. Its primary virtue is that it is much shorter than the other suggestions here.
var parallel = function(actions, finished) {
finishedCount = 0;
var results = [];
$.each(actions, function(i, action) {
action(function(result) {
results[i] = result;
finishedCount++;
if (finishedCount == actions.length) {
finished(results);
}
});
});
};
You pass it an array of functions to run in parallel. Each function should accept another function to which it passes its result (if any). parallel will supply that function.
You also pass it a function to be called when all the operations have completed. This will receive an array with all the results in. So my example was:
refreshButton.click(function() {
parallel([
function(f) {
contentDiv.fadeOut(f);
},
function(f) {
portlet.content(f);
},
],
function(results) {
contentDiv.children().remove();
contentDiv.append(results[1]);
contentDiv.fadeIn();
});
});
So when my refresh button is clicked, I launch jQuery's fadeOut effect and also my own portlet.content function (which does an async get, builds a new bit of content and passes it on), and then when both are complete I remove the old content, append the result of the second function (which is in results[1]) and fadeIn the new content.
As fadeOut doesn't pass anything to its completion function, results[0] presumably contains undefined, so I ignore it. But if you had three operations with useful results, they would each slot into the results array, in the same order you passed the functions.
you could do something like this
var allData = []
$.getJSON("/values/1", function(data) {
allData.push(data);
if(data.length == 2){
processData(allData) // where process data processes all the data
}
});
$.getJSON("/values/2", function(data) {
allData.push(data);
if(data.length == 2){
processData(allData) // where process data processes all the data
}
});
var processData = function(data){
var sum = data[0] + data[1]
$('#mynode').html(sum);
}
Here's an implementation using mbostock/queue:
queue()
.defer(function(callback) {
$.post('/echo/json/', {json: JSON.stringify({value: 1}), delay: 1}, function(data) {
callback(null, data.value);
});
})
.defer(function(callback) {
$.post('/echo/json/', {json: JSON.stringify({value: 3}), delay: 2}, function(data) {
callback(null, data.value);
});
})
.awaitAll(function(err, results) {
var result = results.reduce(function(acc, value) {
return acc + value;
}, 0);
console.log(result);
});
The associated fiddle: http://jsfiddle.net/MdbW2/
With the following extension of JQuery (to can be written as a standalone function you can do this:
$.whenAll({
val1: $.getJSON('/values/1'),
val2: $.getJSON('/values/2')
})
.done(function (results) {
var sum = results.val1.value + results.val2.value;
$('#mynode').html(sum);
});
The JQuery (1.x) extension whenAll():
$.whenAll = function (deferreds) {
function isPromise(fn) {
return fn && typeof fn.then === 'function' &&
String($.Deferred().then) === String(fn.then);
}
var d = $.Deferred(),
keys = Object.keys(deferreds),
args = keys.map(function (k) {
return $.Deferred(function (d) {
var fn = deferreds[k];
(isPromise(fn) ? fn : $.Deferred(fn))
.done(d.resolve)
.fail(function (err) { d.reject(err, k); })
;
});
});
$.when.apply(this, args)
.done(function () {
var resObj = {},
resArgs = Array.prototype.slice.call(arguments);
resArgs.forEach(function (v, i) { resObj[keys[i]] = v; });
d.resolve(resObj);
})
.fail(d.reject);
return d;
};
See jsbin example:
http://jsbin.com/nuxuciwabu/edit?js,console
The most professional solution for me would be by using async.js and Array.reduce like so:
async.map([1, 2, 3, 4, 5], function (number, callback) {
$.getJSON("/values/" + number, function (data) {
callback(null, data.value);
});
}, function (err, results) {
$("#mynode").html(results.reduce(function(previousValue, currentValue) {
return previousValue + currentValue;
}));
});
If the result of one request depends on the other, you can't make them parallel.
Building on Yair's answer.
You can define the ajax promises dynamically.
var start = 1; // starting value
var len = 2; // no. of requests
var promises = (new Array(len)).fill().map(function() {
return $.ajax("/values/" + i++);
});
$.when.apply($, promises)
.then(myFunc, myFailure);
Suppose you have an array of file name.
var templateNameArray=["test.html","test2.html","test3.html"];
htmlTemplatesLoadStateMap={};
var deffereds=[];
for (var i = 0; i < templateNameArray.length; i++)
{
if (!htmlTemplatesLoadStateMap[templateNameArray[i]])
{
deferreds.push($.get("./Content/templates/" +templateNameArray[i],
function (response, status, xhr) {
if (status == "error") { }
else {
$("body").append(response);
}
}));
htmlTemplatesLoadStateMap[templateNameArray[i]] = true;
}
}
$.when.all(deferreds).always(function(resultsArray) { yourfunctionTobeExecuted(yourPayload);
});
I needed multiple, parallel ajax calls, and the jquery $.when syntax wasn't amenable to the full $.ajax format I am used to working with. So I just created a setInterval timer to periodically check when each of the ajax calls had returned. Once they were all returned, I could proceed from there.
I read there may be browser limitations as to how many simultaneous ajax calls you can have going at once (2?), but .$ajax is inherently asynchronous, so making the ajax calls one-by-one would result in parallel execution (within the browser's possible limitation).