I want to queue multiple asynchronous ajax requests using deferred/promise implementation of jquery:
function doSomething() {
console.log('doSomething')};
function makeMultiAjaxRequests1() {
console.log('makeMultiAjaxRequests1')};
function makeMultiAjaxRequests2() {
console.log('makeMultiAjaxRequests2')};
var step1 = function () {
var promise = new $.Deferred().promise();
makeMultiAjaxRequests1();
return promise; }
var step2 = function () {
var promise = new $.Deferred().promise();
makeMultiAjaxRequests2();
return promise; }
step1()
.then(step2())
.done(doSomething());
$.when(step1(),
step2())
.done(function () {
doSomething();
});
Here is the fiddle link. So my question is:
In the pattern where step1 and step2 are executed in parallel, the code does not reach the last handler function. Why?
You need to resolve the deferred obj in step1 and step2
Try this
function doSomething() {
console.log('doSomething')};
function makeMultiAjaxRequests1(deferred) {
console.log('makeMultiAjaxRequests1')
deferred.resolve()};
function makeMultiAjaxRequests2(deferred) {
console.log('makeMultiAjaxRequests2')
deferred.resolve()};
var step1 = function () {
var deferred = new $.Deferred();
makeMultiAjaxRequests1(deferred);
return deferred; }
var step2 = function () {
var deferred = new $.Deferred();
makeMultiAjaxRequests2(deferred);
return deferred; }
step1().then(step2).done(doSomething);
$.when(step1(), step2()).done(function () {
doSomething();
});
#Daiwei gives a good answer.
A common gist to be referred to is https://gist.github.com/sergio-fry/3917217 by sergio-fry.
Should you want to have a more dynamic approach where you don't know beforehand how many arguments you are running parallel, here is a good example extension of JQuery (1.10+):
$.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 the code in action with a dynamic live example:
http://jsbin.com/nuxuciwabu/edit?js,console
It does reach your done function if you give it a URL it can actually reach (in the case of jsfiddle, that would be say /echo/html/: http://jsfiddle.net/LnaPt/2/
Basically, you just need to do this:
var promise = $.ajax({
type: "GET",
url: "/echo/html/", //<-- instead of google
}).promise();
Related
I have a function which calls dealCardSelectableAI(), which sets up a number of jQuery deferred promises. The function setCardName() is then called from within it. Once both functions complete their tasks saveGame() should then be triggered.
Everything works, except setCardName() does not complete before saveGame() is triggered. It appears that deferredQueue.push(setCardName(system, result)); is not operating as I expected. I am not sure where I'm going wrong or how to resolve the issue.
var setCardName = function (system, card) {
var deferred = $.Deferred();
require(["cards/" + card[0].id], function (data) {
var cardName = loc(data.summarize());
system.star.ai().cardName = ko.observable(cardName);
deferred.resolve();
});
return deferred.promise();
};
var dealCardSelectableAI = function (win, turnState) {
var deferred = $.Deferred();
// Avoid running twice after winning a fight
if (!win || turnState === "end") {
var deferredQueue = [];
_.forEach(model.galaxy.systems(), function (system, starIndex) {
if (
model.canSelect(starIndex) &&
system.star.ai() &&
system.star.ai().treasurePlanet !== true
) {
deferredQueue.push(
chooseCards({
inventory: inventory,
count: 1,
star: system.star,
galaxy: game.galaxy(),
addSlot: false,
}).then(function (result) {
deferredQueue.push(setCardName(system, result));
system.star.cardList(result);
})
);
}
});
$.when(deferredQueue).then(function () {
deferred.resolve();
});
} else {
deferred.resolve();
}
return deferred.promise();
};
dealCardSelectableAI(false).then(saveGame(game, true));
Your code says call saveGame() and what is returned from the function call should be set to then. It is not saying, "call saveGame when done"
dealCardSelectableAI(false).then(function () { saveGame(game, true) });
I wish to call dealCardSelectableAI(), have it chooseCards(), then use the output to set an observable system.star.cardList(), then call setCardName(). Once all this is done I want saveGame() to execute.
However, setCardName() is not completing before saveGame() is called, so apparently I can't push it into my deferredQueue via a .then().
I'm using jQuery due to working within an ES5 environment.
var setCardName = function (system, card) {
var deferred = $.Deferred();
require(["cards/" + card[0].id], function (data) {
var cardName = loc(data.summarize());
system.star.ai().cardName = cardName;
deferred.resolve();
});
return deferred.promise();
};
var dealCardSelectableAI = function (win, turnState) {
var deferred = $.Deferred();
// Avoid running twice after winning a fight
if (!win || turnState === "end") {
var deferredQueue = [];
_.forEach(model.galaxy.systems(), function (system, starIndex) {
if (
model.canSelect(starIndex) &&
system.star.ai() &&
system.star.ai().treasurePlanet !== true
) {
deferredQueue.push(
chooseCards({
inventory: inventory,
count: 1,
star: system.star,
galaxy: game.galaxy(),
addSlot: false,
}).then(function (card) {
system.star.cardList(card);
deferredQueue.push(setCardName(system, card));
})
);
}
});
$.when(deferredQueue).then(function () {
deferred.resolve();
});
} else {
deferred.resolve();
}
return deferred.promise();
};
dealCardSelectableAI(false).then(function () {
saveGame(game, true);
});
I tried resolving this by changing the function calls so setCardName() was chained following dealCardSelectableAI(). However, it relies on system.star.cardList() having been written, which in some circumstances had not yet been done.
Given the dependency system.star.cardList() has on chooseCards(), I cannot figure out how to make sure it has been written to before calling setCardName() in a way which blocks saveGame() until everything is done.
I'm new to this kind of problem in javascript and i can't fix this attempt to wait for an asynchronous call combining Angular promise objects and timeouts.
The function onTimeout seems never execute.
getAsyncContent: function (asyncContentInfos) {
var deferObj = $q.defer();
var promiseObj = deferObj.promise;
asyncContentInfos.promiseObject = promiseObj;
var blockingGuard = { done: false };
promiseObj.then(function () {
blockingGuard.done = true;
});
this.wait = function () {
var executing = false;
var onTimeout = function () {
console.log("******************** timeout reached ********************");
executing = false;
};
while (!blockingGuard.done) {
if (!executing && !blockingGuard.done) {
executing = true;
setTimeout(onTimeout, 200);
}
}
};
$http.get(asyncContentInfos.URL, { cache: true })
.then(function (response) {
asyncContentInfos.responseData = response.data;
console.log("(getAsyncContent) asyncContentInfos.responseData (segue object)");
console.log(asyncContentInfos.responseData);
deferObj.resolve('(getAsyncContent) resolve');
blockingGuard.done = true;
return /*deferObj.promise*/ /*response.data*/;
}, function (errResponse) {
var err_msg = '(getAsyncContent) ERROR - ' + errResponse;
deferObj.reject(err_msg);
console.error(err_msg);
});
return {
wait: this.wait
}
}
Client code is something like this:
var asyncVocabulary = new AsyncContentInfos(BASE_URL + 'taxonomy_vocabulary.json');
getAsyncContent(asyncVocabulary).wait();
And AsyncContentInfos is:
function AsyncContentInfos(URL) {
this.URL = URL;
this.responseData = [];
this.promiseObject;
}
$http.get returns a promise which will resolve when the call completes. Promises are a way to make asyncronous more clean and straight lined than plain old callbacks.
getAsyncContent: function (asyncContentInfos) {
return $http.get(asyncContentInfos.URL, { cache: true })
.then(function (response) {
return response.data;
}, function (errResponse) {
console.error(err_msg);
throw errResponse;
});
}
Then using it:
getAsyncContent({...}).then(function(yourDataIsHere) {
});
The nice thing about promises is that they can be easily chained.
getAsyncContent({...})
.then(function(yourDataIsHere) {
return anotherAsyncCall(yourDataIsHere);
})
.then(function(your2ndDataIsHere) {
});
I have this class:
(function(){
"use strict";
var FileRead = function() {
this.init();
};
p.read = function(file) {
var fileReader = new FileReader();
var deferred = $.Deferred();
fileReader.onload = function(event) {
deferred.resolve(event.target.result);
};
fileReader.onerror = function() {
deferred.reject(this);
};
fileReader.readAsDataURL(file);
return deferred.promise();
};
lx.FileRead = FileRead;
}(window));
The class is called in a loop:
var self = this;
$.each(files, function(index, file){
self.fileRead.read(file).done(function(fileB64){self.fileShow(file, fileB64, fileTemplate);});
});
My question is, is there a way to call a method once the loop has completed and self.fileRead has returned it's deferred for everything in the loop?
I want it to call the method even if one or more of the deferred fails.
$.when lets you wrap up multiple promises into one. Other promise libraries have something similar. Build up an array of promises returned by fileRead.read and then pass that array to $.when and hook up then/done/fail/always methods to the promise returned by .when
// use map instead of each and put that inside a $.when call
$.when.apply(null, $.map(files, function(index, file){
// return the resulting promise
return self.fileRead.read(file).done(function(fileB64){self.fileShow(file, fileB64, fileTemplate);});
}).done(function() {
//now everything is done
})
var self = this;
var processFiles = function (data) {
var promises = [];
$.each(files, function (index, file) {
var def = data.fileRead.read(file);
promises.push(def);
});
return $.when.apply(undefined, promises).promise();
}
self.processFiles(self).done(function(results){
//do stuff
});
$.when says "when all these promises are resolved... do something". It takes an infinite (variable) number of parameters. In this case, you have an array of promises;
I know this is closed but as the doc states for $.when: In the multiple-Deferreds case where one of the Deferreds is rejected, jQuery.when immediately fires the failCallbacks for its master Deferred. (emphasis on immediately is mine)
If you want to complete all Deferreds even when one fails, I believe you need to come up with your own plugin along those lines below. The $.whenComplete function expects an array of functions that return a JQueryPromise.
var whenComplete = function (promiseFns) {
var me = this;
return $.Deferred(function (dfd) {
if (promiseFns.length === 0) {
dfd.resolve([]);
} else {
var numPromises = promiseFns.length;
var failed = false;
var args;
var resolves = [];
promiseFns.forEach(function (promiseFn) {
try {
promiseFn().fail(function () {
failed = true;
args = arguments;
}).done(function () {
resolves.push(arguments);
}).always(function () {
if (--numPromises === 0) {
if (failed) {
//Reject with the last error
dfd.reject.apply(me, args);
} else {
dfd.resolve(resolves);
}
}
});
} catch (e) {
var msg = 'Unexpected error processing promise. ' + e.message;
console.error('APP> ' + msg, promiseFn);
dfd.reject.call(me, msg, promiseFn);
}
});
}
}).promise();
};
To address the requirement, "to call the method even if one or more of the deferred fails" you ideally want an .allSettled() method but jQuery doesn't have that particular grain of sugar, so you have to do a DIY job :
You could find/write a $.allSettled() utility or achieve the same effect with a combination of .when() and .then() as follows :
var self = this;
$.when.apply(null, $.map(files, function(index, file) {
return self.fileRead.read(file).then(function(fileB64) {
self.fileShow(file, fileB64, fileTemplate);
return fileB64;//or similar
}, function() {
return $.when();//or similar
});
})).done(myMethod);
If it existed, $.allSettled() would do something similar internally.
Next, "in myMethod, how to distinguish the good responses from the errors?", but that's another question :)
Basically I have the function getUserInfo which has one function that returns available and assigned groups within the service. Then I have the other two functions below return those objects. However, I can't run the getAssignedGroups() and getAvailableGroups() before the first function is done. So I thought I'd use the then() to ensure those two ran once the first function was completed.
I have this function in a controller:
$scope.getUserInfo = function(selectedUser) {
$scope.userGroupInfo = groupService.getUserGroups(selectedUser.domain,$scope.groups).then(
$scope.assignedGroups = groupService.getAssignedGroups(),
$scope.availableGroups = groupService.getAvailableGroups()
);
};
This is my service:
spApp.factory('groupService', function () {
var assignedGroups, availableGroups, allGroups;
var getGroups = function () {
allGroups = [];
$().SPServices({
operation: "GetGroupCollectionFromSite",
completefunc: function(xData, Status) {
var response = $(xData.responseXML);
response.find("Group").each(function() {
allGroups.push({
id: $(this).attr('ID'),
name: $(this).attr('Name'),
Description: $(this).attr('Description'),
owner: $(this).attr('OwnerID'),
OwnerIsUser: $(this).attr('OwnerIsUser'),
});
});
}
});
return allGroups;
}
var getUserGroups = function (selectedUser, allGroups) {
assignedGroups = [];
$().SPServices({
operation: "GetGroupCollectionFromUser",
userLoginName: selectedUser,
completefunc: function(xData, Status) {
var response = $(xData.responseXML);
response.find("errorstring").each(function() {
alert("User not found");
booErr = "true";
return;
});
response.find("Group").each(function() {
assignedGroups.push({
id: $(this).attr('ID'),
name: $(this).attr('Name'),
Description: $(this).attr('Description'),
owner: $(this).attr('OwnerID'),
OwnerIsUser: $(this).attr('OwnerIsUser'),
});
});
}
});
//from here I start comparing All Groups with user groups to return available groups
var assignedGroupsIds = {};
var groupsIds = {};
var availableGroups = [];
assignedGroups.forEach(function (el, i) {
assignedGroupsIds[el.id] = assignedGroups[i];
});
allGroups.forEach(function (el, i) {
groupsIds[el.id] = allGroups[i];
});
for (var i in groupsIds) {
if (!assignedGroupsIds.hasOwnProperty(i)) {
availableGroups.push(groupsIds[i]);
}
}
/* return {
assignedGroups:assignedGroups,
availableGroups:availableGroups
}*/
}
var getAvailableGroups = function () {
return availableGroups;
}
var getAssignedGroups = function () {
return assignedGroups;
};
return {
getGroups:getGroups,
getUserGroups:getUserGroups,
getAvailableGroups: getAvailableGroups,
getAssignedGroups:getAssignedGroups
}
});
You can inject the Angular promise module into your factory:
spApp.factory('groupService', function ($q) {
Then inside the getUserGroups() function of your factory, declare a deferred object:
var deferred = $q.defer();
Then you need to use deferred.resolve(response) inside your async request and return deferred.promise from your function. Also, the then function takes a function with the returned response as the argument (so you can then access the response from the controller):
$scope.userGroupInfo = groupService.getUserGroups(selectedUser.domain,$scope.groups).then(function(resp) {
$scope.assignedGroups = groupService.getAssignedGroups(),
$scope.availableGroups = groupService.getAvailableGroups()
});
Look into the AngularJS docs on $q for more info.
Better approach will be use callback approach. You can take following approach.
$scope.getUserInfo = function(selectedUser, getUserInfoCallback) {
$scope.userGroupInfo = groupService.getUserGroups(selectedUser.domain,$scope.groups, function (response){
$scope.assignedGroups = groupService.getAssignedGroups( function (response){
$scope.availableGroups = groupService.getAvailableGroups( function(response){
//Here call parent callback
if(getUserInfoCallback)
{
getUserInfoCallback(response); //If you need response back then you can pass it.
}
})
})
})
);
};
Now you need to define each method as callback. Following is sample method for your reference.
$scope.getAssignedGroups = function (getAssignedGroupsCallback){
//Do all operation
//Now call callback
if(getAssignedGroupsCallback)
{
getAssignedGroups();//you can pass data here which you would like to get it return
}
};
Note: I have just added the code to clarify the approach. You need to change it to compile and implement your own logic.
Summary of approach: All services are invoked asynchronously therefore you need to pass callback method as chain (to keep your code clean) so that your code can wait for next step.
Hope it helps.