I want to make some API call if the status is 'ready' and then once only after that resolves I want to execute some statements.
If the status is not ready I don't want to make the API call but will still execute the statements.
I have it done it like this :
if(job.status === 'ready')
//Makes a promise to fetch the progress API details for ready batches only
var promise = HttpWrapper.send('/api/jobs/'+job.job_id+'/getDetails', { "operation": 'GET' });
//Once the promise is resolved, proceed with rest of the items
$q.all([promise])
.then(function(result) {
//Because for not ready batches promise object and it's response wuld be undefined
if(result[0] !== undefined){
//Create a property that would hold the progress detail for ready batches
job.pct = result[0].pct;
}
//Want to execute these lines no matter what
vm.job = job;
vm.loading = false;
I know I am making some bad coding practices here .
I may not need $q.all at all.
But I can't figure out how to handle the situation - because the last 2 lines would be executed
For ready batches within then only after that promise resolves, but for other batches there is no promise. So they can get executed quickly.
How can I effectively write them so that both the situations are handled?
This should work, for lines to execute regardless I recommend trying the .finally block. you can check the job status then call the job details function.
if (job.status === 'ready') {
getJobDetails(job);
} else {
defaults(job);
}
function getJobDetails(job) {
return $http.get('/api/jobs/' + job.job_id + '/getDetails')
.then(function(resp) {
if (resp) {
job.pct = result[0].pct;
}
})
.catch(funcition(error) {
console.log(error);
})
.finally(function() {
vm.job = job;
vm.loading = false;
});
}
function defaults(job) {
vm.job = job;
vm.loading = false;
}
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 the following cloud function returning immediately, with promise full-filled but without doing its job. Can any one see why?
function myFunction(newValArray)
{
console.log("Entered myFunction.");
var query,classPromise;
query = new Parse.Query("myClass");
classPromise = (query.find().then
(function(result) {
result[0].set("myField", result[0].get("myField")+1);
result[0].save(null,{}).then
(function() {
console.log("1)newValArray:"+newValArray.length.toString());
newValArray.push(result[0].get("myField"));
console.log("2)newValArray:"+newValArray.length.toString());
return Parse.Promise.as();
});
}));
return Parse.Promise.when(classPromise);
}
If I then use this code for :
myFunction(newLTR).then
(function() {
console.log("myFunction FULL-FILLED.");
}
I can see the messages "Entered myFunction." and "myFunction FULL-FILLED." in the logs.
But I never see "1)newValArray:..." neither do I see "2)newValArray:..."
I have also checked that the passed parameter has not been processed as expected.
If I replace myFunction with the following version, it doesn't make any difference:
function myFunction(newValArray)
{
console.log("Entered myFunction.");
var query,classPromise;
query = new Parse.Query("Configuration");
classPromise = (query.find().then
(function(result) {
result[0].set("myField", result[0].get("myField")+1);
result[0].save(null,{
success:function(configRcd) {
console.log("1)newValArray:"+newValArray.length.toString());
newValArray.push(configRcd.get("myField"));
console.log("2)newValArray:"+newValArray.length.toString());
return Parse.Promise.as();
},
error:function(error) {
console.log("Something went wrong in incrementLastTouchReference.");
}});
}));
return Parse.Promise.when(classPromise);
}
That's a terrible way to write your promises. The whole reason you want to use promises in the first place, is so you can chain callbacks. In your example it's the worst of both worlds, the complexity of promises but you're still nesting.
The second issue is that you really need to place a final error handler. Any errors emitted right now might just disappear. always end with a catch.
I rewrote your first function to correctly do promises, but I can't guarantee if there's not something else wrong. Hopefully it helps you along your way:
function myFunction(newValArray)
{
console.log("Entered myFunction.");
var query,classPromise;
query = new Parse.Query("myClass");
classPromise = query.find()
.then(function(result) {
result[0].set("myField", result[0].get("myField")+1);
return result[0].save(null,{});
}).then(function() {
console.log("1)newValArray:" + newValArray.length.toString());
newValArray.push(result[0].get("myField"));
console.log("2)newValArray:"+newValArray.length.toString());
return Parse.Promise.as();
}).then(function(result) {
// I added this third then clause. You were returning
// Parse.Promise.as() so presumably you wanted to do something
// with that. Before this then clause it got discarded, with my
// change the result of Parse.Promise.as() is thrown in the
// 'result' argument in this function.
}).catch(function(err) {
// If an error is thrown in any part of the change, it will
// bubble to this final catch statement.
// Do something with err! Log it or whatever ;)
})
return Parse.Promise.when(classPromise);
}
I'm new to AngularJS and Breeze. I'm trying to save changes and have a problem with that. Here's my code:
In controller:
function update() {
vm.loading = true;
return datacontext.saveSettings().then(function () {
vm.loading = false; // never gets called
}).fail(function (data) {
vm.loading = false; // never gets called
});
}
In datacontext:
function saveSettings() {
if (manager.hasChanges()) {
manager.saveChanges() // breaks here if there are changes
.then(saveSucceeded)
.fail(saveFailed)
.catch(saveFailed);
} else {
log("Nothing to save");
return false;
};
}
The error is thrown in angular.js and it's very unhelpful TypeError: undefined is not a function I guess there is something simple I'm missing here, but can't figure out what is it.
Want to note that it does send correct data to SaveChanges method on server, but the error is thrown before any response from the server received. After the response is received it throws another error TypeError: Cannot read property 'map' of undefined but it might be related to the fact the response I return is invalid. I haven't got to that part yet.
Can anyone anyone help with it? I'm lost here.
UPDATE
Here is how I construct my dataservice and manager:
var serviceName = "http://admin.localhost:33333/api/breeze/"; //
var ds = new breeze.DataService({
serviceName: serviceName,
hasServerMetadata: false,
useJsonp: true,
jsonResultsAdapter: jsonResultsAdapter
});
var manager = new breeze.EntityManager({ dataService: ds });
model.initialize(manager.metadataStore);
Two problems:
Your datacontext method does not return a promise so the caller cannot find anything to hang the then or fail call on.
You should be callingcatch, not fail
1. Return a promise
Your saveSettings method did not return a result in the success case so it must fail. Your method must also return a promise in the fail case ... or it will also fail.
And while I'm here, since there is no real difference between your success and fail case, you might as well move the vm.loading toggle to the finally clause.
Try this instead:
function update() {
vm.loading = true;
return datacontext.saveSettings()
.then(function () {
// .. success handling if you have any
})
.catch(function (data) {
// .. fail handling if you have any
})
.finally(funtion() {
vm.loading = false; // turn it off regardless
});
}
And now the dataContext ... notice the two return statements return a promise.
function saveSettings() {
if (manager.hasChanges()) {
return manager.saveChanges()
.then(saveSucceeded)
.catch(saveFailed);
} else {
log("Nothing to save");
// WHY ARE YOU FAILING WHEN THERE IS NOTHING TO SAVE?
// Breeze will handle this gracefully without your help
return breeze.Q.reject(new Error('Nothing to save'));
};
}
2. Use catch
I assume you have configured Breeze to use Angular's $q for promises (you should be using the "breeze.angular" service and have injected "breeze" somewhere).
$q does not have a fail method! The equivalent is catch. For some reason you have both attached to your query. You'll get the ReferenceError exception immediately, before the server has a chance to respond ... although it will launch the request and you will get a callback from the server too.
Try just:
return manager.saveChanges()
.then(saveSucceeded)
.catch(saveFailed);
You see many Breeze examples that call fail and fin. These are "Q.js" methods; "Q.js" is an alternative promise library - one used by Breeze/KnockOut apps and it was the basis for Angular's $q.
Both "Q.js" and $q support the now-standard catch and finally promise methods. We're slowly migrating our example code to this standard. There is a lot of old fail/finally code around in different venues. It will take time.
Sorry for the confusion.
Update savesetting function like below to return Promise.
function saveSettings() {
if (manager.hasChanges()) {
return manager.saveChanges(); // return promise
} else {
log("Nothing to save");
return false;
};
}
Then you can call then and fail in update function like following.
function update() {
vm.loading = true;
return datacontext.saveSettings().then(function () {
vm.loading = false; // never gets called
}).fail(function (data) {
vm.loading = false; // never gets called
});
}
I have a javascript function that posts data to a validation script and grabs a value from there. The callback function on the post request returns a boolean value, and I'm trying to get the entire function to return that boolean value. Right now, the callback function returns the correct value, but the function itself doesn't return anything. Here's the code:
function validate(request_type, request_text) {
$.post("http://www.example.com/ajax/validate.php",{
type: request_type,
text: request_text
}, function(data) {
return (data == "valid");
});
}
I realise that this is sort of a "synchronous" call, and that's not what AJAX is about, but I already have numerous functions in validate.php (database calls, etc.) that I can't implement in Javascript, and I saw threads like this one that talk about using some form of handler.
How would I write a simple handler that will make either the variable data or the result of the boolean comparison data == "valid" available when I use it in an if/else statement (which is where this function is supposed to be used)?
EDIT: For example, one of the if statements that will be using the boolean result:
if (!validate('password',pass_new)) {
$('#pass_new').addClass('error');
$('#pass_confirm_new').addClass('error');
$(error_string.format('Please enter a valid password.')).insertAfter('#pass_confirm_new');
$('#pass_text_short').hide();
$('#pass_text_long').show();
EDIT: The function called with the onsubmit event in my HTML form:
function valid_pass_sett() {
//code to remove errors left over from previous submissions - snipped
pass_old = $('input[name=pass_old]').val();
pass_new = $('input[name=pass_new]').val();
pass_confirm_new = $('input[name=pass_confirm_new]').val();
//some if statements that don't involve AJAX requests - snipped
if (!validate('password',pass_new)) {
$('#pass_new').addClass('error');
$('#pass_confirm_new').addClass('error');
$(error_string.format('Please enter a valid password.')).insertAfter('#pass_confirm_new');
$('#pass_text_short').hide();
$('#pass_text_long').show();
return false;
}
return true;
}
I haven't edited this code to include the updated code that's been posted, but my question is how I return false from it to stop form submission?
function validate(request_type, request_text, callback) {
$.post("http://www.example.com/ajax/validate.php",{
type: request_type,
text: request_text
}, function(data) {
callback(data == "valid");
});
}
And usage would be:
validate(request_type, request_text, function (isValid) {
if(isValid) {
// do something
} else {
// do something if invalid
}
});
Unless you make a synchronous AJAX call (which you probably don't want to do), you simply can't.
If this function is used in several places in your code, your best bet may be to allow it to receive a function.
That way instead of relying on the result being returned from your function to be used in some code, you're actually passing your code directly in, so it is ensured to be able to use the response.
var my_form = $('#my_form');
my_form.submit( valid_pass_sett );
function valid_pass_sett() {
//code to remove errors left over from previous submissions - snipped
pass_old = $('input[name=pass_old]').val();
pass_new = $('input[name=pass_new]').val();
pass_confirm_new = $('input[name=pass_confirm_new]').val();
validate('password', pass_new, pswd_validation_callback); // async validation
return false; // cancel form submission
}
function validate(request_type, request_text, callback ) {
$.post("http://www.example.com/ajax/validate.php",{
type: request_type,
text: request_text
}, callback );
}
function pswd_validation_callback( data ) {
if ( data === 'valid' ) {
// if valid, call the native .submit() instead of the jQuery one
my_form[ 0 ].submit();
} else {
// Otherwise do your thing for invalid passwords.
// The form has already been canceled, so no concerns there.
$('#pass_new').addClass('error');
$('#pass_confirm_new').addClass('error');
$(error_string.format('Please enter a valid password.')).insertAfter('#pass_confirm_new');
$('#pass_text_short').hide();
$('#pass_text_long').show();
}
}
EDIT: Changed to use code posted in question.
EDIT: Updating to work with additional code posted. Narrowing answer down to the named function for clarity.
function validate(request_type, request_text) {
$.post("http://www.example.com/ajax/validate.php",{
type: request_type,
text: request_text
}, function(data) {
return (data == "valid");
}); }
You can't really return from 'validate' the result of the AJAX call. You could try declare a variable before the $.post call, let's call it 'x', and inside the response function assign the value to that variable (x=data=="valid"), and outside the $.post block, but inside the 'validate' function, return that value.
function validate(request_type, request_text) {
var x;
$.post("http://www.example.com/ajax/validate.php",{
type: request_type,
text: request_text
}, function(data) {
x = data == "valid";
});
return x; }
The real problem is that the function 'validate' will continue even if the post call haven't return any value, so it will always be 'false'.
The best thing you can do is call another function INSIDE the response function, so you can assure that the server call is over before getting to the next part.
Edit:
It's been a long time since I posted this answer. The world has changed and so AJAX calls.
Now we have promises ;)
You still cannot return a direct value from a function, but you can return a Promise object, which can be chanined to another Promise, and the second promise will get the data you returned from the first one.
function validate(request_type, request_text) {
var promise = $.ajax("http://www.example.com/ajax/validate.php",{
type: request_type,
text: request_text
});
function getStuff(data) {
//Do something and return the data to the next promise
return data;
}
promise.then(getStuff).then(function(data){
// Do something else with data
});
}
If I understand this question correctly you can achieve what you want by simply storing the returned value into a HTML element and then return that elements value from your custom function:
function validate(request_type, request_text){
$.post("http://www.example.com/ajax/validate.php",{
type: request_type,
text: request_text},
function(data) {
$('#someElement').text(data);
});
//return the data by getting the value of the html element
return $('#someElement').text();
}