Why is then() chained methods not running sequentially? - javascript

We are trying to execute a number of AJAX calls in a particular order. The following code has methodA, methodB and methodC (each returns an AJAX promise object running async=true).
They are chained using the then() function in jQuery.
self.methodA().then( self.methodB() ).then( self.methodC() )
I have made one of the methods slow (methodB) (I use a slow URL).
I would expect A... 10 second wait...then B then C.
Instead I get A, C ....10 second wait and B.
Why is it doing that? Does it have something to do with me using the alert() in an always() function?
Here is my code in a fiddle :
http://jsfiddle.net/h8tfrvy4/13/
Code:
function Tester() {
var self = this;
this.url = 'https://public.opencpu.org/ocpu/library/';
this.slowurl = 'http://fake-response.appspot.com/?sleep=5';
this.save = function() {
self.methodA().then( self.methodB() ).then( self.methodC() )
}
this.methodA = function () {
var self = this;
return $.ajax({
url: self.url,
async: true
}).always(function (processedDataOrXHRWrapper, textStatus, xhrWrapperOrErrorThrown) {
//check for errors... and if OK
alert('A OK');
})
}
this.methodB = function () {
var self = this;
return $.ajax({
url: self.slowurl,
async: true
}).always(function (processedDataOrXHRWrapper, textStatus, xhrWrapperOrErrorThrown) {
//check for errors... and if OK
alert('B OK');
})
}
this.methodC = function () {
var self = this;
return $.ajax({
url: self.url,
async: true
}).always(function (processedDataOrXHRWrapper, textStatus, xhrWrapperOrErrorThrown) {
//OK
alert('C OK');
})
}
}
new Tester().save();

This is wrong:
self.methodA().then( self.methodB() ).then( self.methodC() )
You're invoking each method immediately, and passing the promises into then.
If you want each function to wait until the previous finishes, you need to give each then a callback to execute when the previous promise resolves:
self.methodA().then(function () { return self.methodB() }).then(function() { return self.methodC() });

Short and simple:
this.save = function() {
self.methodA().then( self.methodB ).then( self.methodC )
}
It has bothered me all **&^*$& day that #meagar was right and I was wrong on this one but I was sure that I was right. His answer seemed too complicated and but I was fuzzy headed in the morning and my answer wasn't right either. This is the right answer and it works perfectly when you plug it into the JSFiddle.

Related

promise with ajax doesn't return any value in jquery

My script:
var testApp = (function($){
var data = [{
"layout": "getSample",
"view": "conversations",
"format": "json",
}];
var Data = 'default';
function ajaxCall(opt) {
return new Promise(function(resolve, reject) {
jQuery.ajax({
method: "POST",
url: localStorage.getItem("root")+"/index.php",
"data": opt,
error: function() {
alert('error');
},
success: function(result) {
console.debug(result);
resolve(result);
}//end success
});//end ajax
});//end promise
}
return {
render: function(opt) {
if(typeof opt === 'object') {
var list = {
data : [opt]
}
//here I'm passing list object's data to be used in ajaxCall function.That's the reeason I used call method. It's data is passed from another page.
ajaxCall.call (list, list.data).then(function(v) {
console.log("v "+v); // nothing happens yet...expecting for the success object to be passed here
}).catch(function(v) {
//nothing to do yet
});
}
}
};//end return
})(jQuery);
Is the correct way of using promise with ajax?
ajaxCall.call (list, list.data).then(function(v) {
console.log("v "+v); // doesn't return anything
}).catch(function(v) {
//nothing to do yet
});
referred: How do I return the response from an asynchronous call?
well, its a simple fix I found..
//below line of code, moved above return new promise and it worked
var opt = jQuery.extend({}, data[0], opt[0]);
jQuery Ajax functions already return promises. You don't have to turn them into promises manually.
var testApp = (function($) {
var ajaxDefaults = {
"layout": "getSample",
"view": "conversations",
"format": "json",
};
// this can be re-used in all your Ajax calls
function handleAjaxError(jqXhr, status, error) {
console.error('Ajax error', error);
});
function ajaxCall(opt) {
var url = localStorage.getItem("root") + "/index.php",
data = jQuery.extend({}, ajaxDefaults, opt);
return $.post(url, data).fail(handleAjaxError);
}
return {
render: function(opt) {
return ajaxCall(opt).then(function (result) {
console.log("v " + result);
return result;
});
}
};
})(jQuery);
You don't need to use .call() to call a function. It doesn't make a lot of sense in this case, either. If it is not an object method, but a stand-alone function, call it normally and pass arguments.
There is no guarantee that localStorage.getItem("root") contains any value, but your code ignores this possibility. That's a bug.
You don't want two variables data and Data in your code. Don't set up trip wires like this.
There is no need to use $.ajax() when $.post()/$.get() can do the job in one line.
Return something from your render() method and from its .then() handler, too, so you can chain more code elsewhere in your application, e.g.
app.render({data: 1234}).then(function (result) {
// ...
});

Backbone + Promises - How to fetch after post

I have a model which has two functions - one posts, and one gets.
The fetch:
fetch: function (options) {
var self = this;
return P1Comm.get({
'dataType': 'json',
'processAjaxResponse': self.processAjaxResponse,
'onStatusInvalid': function (e) {
P1.log(e, 'status');
},
'onSuccess': options.success,
'onError': function (e) {
P1.log(e);
},
'sourceURL': P1.API_APPS_ROOT + 'v1.0/accepted-terms'
});
},
The post:
acceptTerms: function (appId) {
var self = this;
self.set({
'app_id': parseInt(appId,10)
});
self.createEdit(self.toJSON(), {
}).pipe(function () {
var def = $.Deferred();
var saveOpts = {
dataType: 'json',
stringify: true,
contentType: 'application/json',
processData: false,
processAjaxResponse: self.processAjaxResponse
};
self.save(self.toJSON(), saveOpts);
return def.promise();
});
},
Calling the post from the view: acceptAppTerms.acceptTerms(1);
These both work in their own right but I want to change this so that:
- Make the POST acceptTerms()
- Then make the GET fetch()
- Then call another function
I think it would be something like this (at least for the first two points):
acceptAppTerms.acceptTerms(id).then(function () {
this.launchApp(event, id);
});
But I get the error of Uncaught TypeError: Cannot read property 'then' of undefined
I am not that good at front-end - can someone point me in the right direction?
Thanks
UPDATE:
fetchAcceptedTerms: function () {
var self = this;
this.appAcceptedTerms = new T1AppAcceptedTerms();
this.acceptedTerms = new AppAcceptedTerms();
this.acceptedTerms.fetch({
success: function (data) {
if (data.meta.status === 'success') {
self.appAcceptedTerms.set(data.data);
}
}
});
},
Example below works but it breaks the setting of the data into the model.
The reason you get the error is because your acceptTerms doesn't return anything, or in other words returns undefined which doesn't have a then() method.
Your code should be something like:
fetch: function(options) {
var self = this;
return P1Comm.get({
dataType: 'json',
processAjaxResponse: self.processAjaxResponse,
onStatusInvalid: function(e) {
P1.log(e, 'status');
},
onSuccess: options.success,
onError: function(e) {
P1.log(e);
},
sourceURL: P1.API_APPS_ROOT + 'v1.0/accepted-terms'
});
},
acceptTerms: function(appId) {
var self = this;
self.set({
'app_id': parseInt(appId, 10)
});
return self.createEdit(self.toJSON(), {}).pipe(function() {
//---------------------------------------^ better use .then()
var saveOpts = {
dataType: 'json',
stringify: true,
contentType: 'application/json',
processData: false,
processAjaxResponse: self.processAjaxResponse
};
return self.save(self.toJSON(), saveOpts);
});
},
This code asummes that P1Comm.get, self.createEdit and self.save returns a promise object. If they don't then you need to create a Deferred object and return it's promise from these functions. And inside the success/error callbacks of their asynchronous actions you need to resolve/reject the promise accordingly.
I'd also like to mention that .pipe() is a deprecated method, you should use then() unless you're using ancient version of jQuery.

How to optimize (minimize) jQuery AJAX calls

I have over 50 AJAX calls from different functions of my code. All these calls have a similar structure with different data/url/callback params:
var jqXHR = $.post('/dba/port.php', {
mode: "del_wallfunds",
pdata: cdata,
wname: wName
},
function (data) {}, "json")
.done(function (data) {
var msg = data.msg;
if (msg.indexOf("Error") == -1) {
alertify.success(msg);
delSelected(selGroup);
} else {
alertify.error(msg);
}
})
.fail(function () {
alertify.error("Error .....");
});
I am thinking how to write a function that would return that var jqXHR to minimize the total size of the code. It is not a problem to pass all static variables like URL, error strings etc. But the problem is that all callback functions on ".done" are different and I don't know how to pass these callback functions as variables.
One way would be to call a single "universal" function on .done and pass a "switch" variable to that function, but it doesn't seem to be an elegant solution.
Any suggestions how to it in some elegant way?
Thanks
Either pass the done callback function as an argument when calling your function:
function ajaxCall(url, data, doneCallback) {
return $.post(url, data, doneCallback, "json").fail(...);
// or
return $.post(url, data, function() {}, "json").done(doneCallback).fail(...);
}
var jqXhr = ajaxCall('yoururl.php', {key: 'value'}, function(data) {
// do something
});
Or return the jqXhr object from the function, and assign the done callback then:
function ajaxCall(url, data) {
return $.post(url, data, function() {}, "json").fail(...);
}
var jqXhr = ajaxCall('yoururl.php', {key: 'value'});
jqXhr.done(function(data) {
// do something
});
Alternatively switch to using jQuery.ajax() instead, and pass the entire options object in:
function ajaxCall(options) {
return $.ajax(options).fail(...);
}
var jqXhr = ajaxCall({
url: 'yoururl.php',
data: {key: 'value'},
dataType: 'json'
});
jqXhr.done(function(data) {
// do something
});
You can try to :
turn "request successfully returned a treatment error" into a "rejected request",
put the "alertify" processing in a common callback
Here is a sketch of what this could give :
function myAjaxApi(url, data){
var myAjaxCall = $.post(url, data, function (data) {}, "json")
.then(function (data) {
// using .then : change "request succesful with error state"
// to "rejected state"
var msg = data.msg;
if (msg !== undefined && msg.indexOf("Error") >= 0) {
var dfd = $.Deferred();
// try to match the same signature as the "error" option
dfd.reject(this, msg);
return dfd;
} else {
return data
}
});
myAjaxCall.done(function(data){
if (data.msg) {
alertify.success(data.msg);
}
}).fail(function (jqxhr, msg) {
if (!msg) { msg = "Error ....."; }
alertify.error(msg);
});
return myAjaxCall;
}
//usage
myAjaxApi('/dba/port.php', {mode: "del_wallfunds", pdata: cdata, wname: wName})
.done(function (data) {
// the ".done()" queue will not be executed if msg contains "Error" ...
delSelected(selGroup);
});
Some parts should be written with more care ; the above example is meant to illustrate how you can wrap your repeated ajax calls inside a common api.

How to wait ajax callback result from another callback?

I have a method below:
self.getOrAddCache = function (key, objectFactory) {
var data = self.getFromCache(key);
if (!data) {
data = objectFactory();
if (data && data != null)
self.addToCache(key, data);
}
return data;
};
I use like this:
function getCities()
{
var cities = getOrAddCache(CacheKeys.Cities, function() {
var cityArray = new Array();
// get city informations from service
$.ajax({
type: "GET",
async: true,
url: "service/cities",
success: function (response) {
$.each(response, function(index, value) {
cityArray.push({
name: value.name,
id: value.id
});
});
}
});
if (cityArray.length > 0)
return cityArray;
else {
return null;
}
});
return cities;
}
getCities function always return null because getCities not waiting for completion async ajax request.
How can i resolve this problem? (Request must be async)
The best solution for this is to use Deferred objects. Since you require your AJAX call to be asynchronous, you should have your getCities function return a promise to return that data at some point in the future.
Instead of storing the raw data in the cache, you store those promises.
If you request a promise that has already been resolved, that will complete immediately. If there's already a pending request for the cached object, the async AJAX call will be started and all outstanding callbacks waiting for that promise will be started in sequence.
Something like this should work, although this is of course untested, E&OE, etc, etc.
self.getCached = function(key, objectFactory) {
var def = self.getCache(key);
if (!def) {
def = objectFactory.call(self);
self.addToCache(key, def);
}
return def;
}
function getCities() {
return getCached(CacheKeys.Cities, function() {
return $.ajax({
type: 'GET',
url: 'service/cities'
}).pipe(function(response) {
return $.map(response, function(value) {
return { name: value.name, id: value.id };
});
});
});
}
Note the usage of .pipe to post-process the AJAX response into the required format, with the result being another deferred object, where it's actually the latter one that gets stored in your cache.
The usage would now be:
getCities().done(function(cities) {
// use the cities array
});
With a callback:
function getCities(callbackFunction)
{
var cities = getOrAddCache(CacheKeys.Cities, function() {
var cityArray = new Array();
// get city informations from service
$.ajax({
type: "GET",
async: true,
url: "service/cities",
success: function (response) {
$.each(response, function(index, value) {
cityArray.push({
name: value.name,
id: value.id
});
});
callbackFunction(cityArray);
}
});
});
}
getCities(function(cityArray){
// do stuff
});
You can't return the result from a function fetching asynchronously the data.
Change your getCities function to one accepting a callback :
function fetchCities(callback) {
var cities = getOrAddCache(CacheKeys.Cities, function() {
var cityArray = new Array();
// get city informations from service
$.ajax({
type: "GET",
async: true,
url: "service/cities",
success: function (response) {
$.each(response, function(index, value) {
cityArray.push({
name: value.name,
id: value.id
});
});
if (callback) callback(cityArray);
}
});
});
}
And use it like this :
fetchCities(function(cities) {
// use the cities array
});
Note that it's technically possible, using async:true, to make the code wait for the response but don't use it : that's terrible practice and it locks the page until the server answers.
You seem to be contradicting yourself.
Something that is asynchronous, by definition, does not pause the script to wait for the end of it's execution. If it does wait, it cannot be asynchronous.
The best wayto fix this is by adding a callback function in your ajax success function that passes the end result to another function, which handles the rest of the execution.

Extending jQuery ajax success globally

I'm trying to create a global handler that gets called before the ajax success callback. I do a lot of ajax calls with my app, and if it is an error I return a specific structure, so I need to something to run before success runs to check the response data to see if it contains an error code bit like 1/0
Sample response
{"code": "0", "message": "your code is broken"}
or
{"code": "1", "data": "return some data"}
I can't find a way to do this in jQuery out of the box, looked at prefilters, ajaxSetup and other available methods, but they don't quite pull it off, the bets I could come up with is hacking the ajax method itself a little bit:
var oFn = $.ajax;
$.ajax = function(options, a, b, c)
{
if(options.success)
{
var oFn2 = options.success;
options.success = function(response)
{
//check the response code and do some processing
ajaxPostProcess(response);
//if no error run the success function otherwise don't bother
if(response.code > 0) oFn2(response);
}
}
oFn(options, a, b, c);
};
I've been using this for a while and it works fine, but was wondering if there is a better way to do it, or something I missed in the jQuery docs.
You can build your own AJAX handler instead of using the default ajax:
var ns = {};
ns.ajax = function(options,callback){
var defaults = { //set the defaults
success: function(data){ //hijack the success handler
if(check(data)){ //checks
callback(data); //if pass, call the callback
}
}
};
$.extend(options,defaults); //merge passed options to defaults
return $.ajax(options); //send request
}
so your call, instead of $.ajax, you now use;
ns.ajax({options},function(data){
//do whatever you want with the success data
});
This solution transparently adds a custom success handler to every $.ajax() call using the duck punching technique
(function() {
var _oldAjax = $.ajax;
$.ajax = function(options) {
$.extend(options, {
success: function() {
// do your stuff
}
});
return _oldAjax(options);
};
})();
Here's a couple suggestions:
var MADE_UP_JSON_RESPONSE = {
code: 1,
message: 'my company still uses IE6'
};
function ajaxHandler(resp) {
if (resp.code == 0) ajaxSuccess(resp);
if (resp.code == 1) ajaxFail(resp);
}
function ajaxSuccess(data) {
console.log(data);
}
function ajaxFail(data) {
alert('fml...' + data.message);
}
$(function() {
//
// setup with ajaxSuccess() and call ajax as usual
//
$(document).ajaxSuccess(function() {
ajaxHandler(MADE_UP_JSON_RESPONSE);
});
$.post('/echo/json/');
// ----------------------------------------------------
// or
// ----------------------------------------------------
//
// declare the handler right in your ajax call
//
$.post('/echo/json/', function() {
ajaxHandler(MADE_UP_JSON_RESPONSE);
});
});​
Working: http://jsfiddle.net/pF5cb/3/
Here is the most basic example:
$.ajaxSetup({
success: function(data){
//default code here
}
});
Feel free to look up the documentation on $.ajaxSetup()
this is your call to ajax method
function getData(newUrl, newData, callBack) {
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: newUrl,
data: newData,
dataType: "json",
ajaxSuccess: function () { alert('ajaxSuccess'); },
success: function (response) {
callBack(true, response);
if (callBack == null || callBack == undefined) {
callBack(false, null);
}
},
error: function () {
callBack(false, null);
}
});
}
and after that callback success or method success
$(document).ajaxStart(function () {
alert('ajax ajaxStart called');
});
$(document).ajaxSuccess(function () {
alert('ajax gvPerson ajaxSuccess called');
});

Categories

Resources