I am trying to use CoffeeScript to setup an AJAX callback function like so:
The Pattern
function doAjax(callback)
{
$.ajax(url, data)
.done(function(){
// ... do stuff here ...
callback(true);
}).fail(function(){
callback(false);
});
}
function doSomething()
{
doAjax(function(result){
if (result == true )
console.log('success');
else
console.log('failed');
});
}
I am using the following CoffeeScript to do this (this is within an object):
CoffeeScript
doAjax: (callback) ->
$.getJSON(url)
.done( (data) ->
if something == true
callback(true)
else
callback(false)
).fail( () ->
callback(false)
)
doSomething: () ->
this.doAjax(function:(result)->
if result == true
console.log "true"
else
console.log "false"
It results in the following compiled JavaScript like this:
Compiled JS
MyObject.prototype.doAjax = function(callback) {
return $.getJSON(url).done(function(data) {
if (something == true) {
callback(true); // <--- The error happens here
} else {
callback(false);
}
}).fail(function() {
callback(false);
});
};
MyObject.prototype.doSomething = function() {
return this.doAjax({
"function": function(result) {
var message;
if (result === true) {
return console.log("true");
} else {
return console.log("false");
}
}
});
};
And I get the error (at the marked line above):
Uncaught TypeError: object is not a function
What am I doing wrong in my CoffeeScript here?
change this
this.doAjax(function:(result)->
to this
this.doAjax((result)->
functions in coffeescript are declared with () ->. function:() -> creates an object with a property called function that contains the actual function
Actually you are trying to callback function to perform some operation after successful ajax call, but you are calling the object as function.Define some function and use it to callback.thank you, for further assistance please report to me.
Related
I'd like to receive a response (true or false) from a called function to decide if the function should continue or stop. Look at the following code for better understanding:
function function1() {
function2(); // call function2
// after called function (here I need true or false, to decide if the function should stop or continue)
}
function function2() {
if (condition === value) {
// do something, give function1 a response to continue
} else {
// do something, give function1 a response to stop
}
}
Updated:
function function1() {
console.log('call function2');
function2(); // call function2
// after called function (here I need true or false, to decide if the function should stop or continue)
console.log('back from function2');
}
function function2() {
if (condition === false) {
console.log('condition === false');
return;
}
}
You don't need an else on the statement. check to see if your variable is false and if it is it will return if not the rest of your function will run automatically.
function function1() {
function2(); // call function2
// after called function (here I need true or false, to decide if the function should stop or continue)
}
function function2() {
if (condition === false) {
return;
}
}
If function2 is synchronous you can just return:
function function1() {
if(!function2()){
return
}; // call function2
// after called function (here I need true or false, to decide if the function should stop or continue)
}
function function2() {
if (condition === value) {
return true;
} else {
return false;
}
}
If function 2 does something asynchronous and expects a callback (one of the tags in your question) then it may be easier to write a function that will use function2 and returns a promise.
function function1(condition) {
console.log('calling function 2');
function2AsPromise(condition).then(function(
function2Result
) {
if (!function2Result) {
console.log('function 2 result is false');
return;
}
console.log('function 2 result is true');
});
console.log('exiting function 2');
}
function function2(condition, callback) {
setTimeout(function() {
if (condition) {
callback(true);
} else {
callback(false);
}
}, 2000);
}
function function2AsPromise(condition) {
return new Promise(function(resolve) {
function2(condition, resolve);
});
}
function1(false);
const function1 = check => {
if (check === false) {
return;
} else {
console.log("back from function2");
}
};
function1(false) // console.log doesn't run
function1(true) // console.log runs
make sure that you pass in a Boolean value.
I have written the code
// Handlers
function successHandlerFactory (savedFlag) {
return function (res, savedFlag){
if (res.data && res.status == 200) {
ngcoupon_offerManager.addOffers(res.data.offers, -1, savedFlag);
console.log('offers response', res, 'savedFlag', savedFlag);
} else {
console.error('something is wrong to get offers', res);
}
}
};
var offerSuccessHandler = function() {
return successHandlerFactory();
}();
var savedofferSuccessHandler = function () {
return successHandlerFactory(true);
}();
but apparently its giving out savedFlag undefined every executinon I make.
How come this does not work
The issue is in this part of the code:
function successHandlerFactory (savedFlag) {
return function (res, savedFlag){
...
You're re-declaring savedFlag in the inner function, which ends up being the variable that is captured in the success handler. Try simply removing the second parameter of the returned function.
I want method to prevent the code from the resumption of what he is doing if the condition is not true.
This is my code
function doSomething{
if(1==2){
alert("Can I access to your event?");
}else{
//1 not equals 2, so please die
// I tried die() event; It worked, But i get this error in the console
// Uncaught TypeError: Cannot call method 'die' of undefined
}
}
$(".foo").click(function(){
doSomething();
alert("welcome, 1 == 1 is true");
}
You could just return false within the click handler, I suppose. For example:
function doSomething () {
if(1==2){
alert("Can I access to your event?");
}else{
return false; // tell the click handler that this function barfed
}
}
$(".foo").click(function(){
if(doSomething() === false){ //check to see if this function had an error
return false; //prevent execution of code below this conditional
}
alert("welcome, 1 == 1 is true");
}
Judging from the code, you probably want to just throw an exception ;-)
function doSomething
{
if(1==2){
alert("Can I access to your event?");
}else{
throw 'blah';
}
}
This will unwind the stack immediately until the exception is caught or it reaches the global level.
Try this traditional way
function doSomething () {
if(1==2){
alert("Can I access to your event?");
return true;
}else{
return false
}
}
Usage:
$(".foo").click(function(){
if(doSomething()){
alert("welcome, 1 == 1 is true");
}else{
alert("Sorry, 1 == 1 is false");
}
}
You could throw an exception:
function doSomething (){
if (1 == 2) {
alert("Can I access to your event?");
} else {
throw "this is a fatal error";
}
}
$(".foo").click(function () {
doSomething();
alert("welcome, 1 == 1 is true");
});
FIDDLE
Of course you should handle that exception to not get errors in your log, maybe like so:
$(".foo").click(function () {
try {
doSomething();
alert("welcome, 1 == 1 is true");
} catch (err) {
// do nothing but allow to gracefully continue
}
});
FIDDLE
I have an if statement in php:
if ( $isTrue && db_record_exists($id)) { ... }
else { ... };
The first condition is a true / false boolean check.
The second condition calls a function to see if a row exists in a database table and returns true or false.
I want to rewrite this conditional in Node JS so that it is non-blocking.
I have rewritten db_record_exists as follows...
function db_record_exists(id, callback) {
db.do( "SELECT 1", function(result) {
if (result) { callback(true); }
else { callback(false); }
);
}
...but I can't see how to then incorporate this into a larger if statement, with the boolean check. For example, the following statement doesn't make sense:
if (isTrue and db_record_exists(id, callback)) {
...
}
What is the "node" way to write this?
Any advice would be much appreciated.
Thanks (in advance) for your help.
Check the variable first, then check the result of the async call inside the callback.
if (isTrue) db_record_exists(id, function(r) {
if (r) {
// does exist
} else nope();
});
else nope();
function nope() {
// does not exist
}
You will need to use callbacks for the if and the else part. Then "nest" the and-conditions:
if ($isTrue) {
db_record_exists(id, function(result) {
if (result)
doesExist();
else
doesntExist();
});
else
doesntExist();
For convenience, you could wrap all that in a helper function (and if you need it multiple times, put in a library):
(function and(cond, async, suc, err) {
if (cond)
async(function(r) { (r ? suc : err)(); });
else
err();
})($isTrue, db_record_exists.bind(null, id), function() {
…
}, function() {
…
});
Maybe this way?
function db_record_exists(id, callback) {
db.do( "SELECT 1", function(result) { callback(result ? true : false); });
}
When I run the following codes, the alert popup displays undefined. I thought it would return either true or false instead. Please can someone explain how the checkLoginStatus() function excutes. Thanks.
function checkLoginStatus() {
$.get("func.php", {op:'login_status', r:Math.random()}, function(data) {
if (data == "Yes") {
showSalesView();
return true;
} else {
loginView();
return false;
}
});
}
alert(checkLoginStatus());
There's a couple things wrong.
One, you're performing an asynchronous call within the function, so by the time the call has come back, checkLoginStatus has already returned. It essentially looks like this:
function checkLoginStatus() {
$.get("func.php", {
op: 'login_status',
r: Math.random()
}, function(data) {
if (data == "Yes") {
showSalesView();
return true;
} else {
loginView();
return false;
}
});
// return undefined
}
Second, you're returning within the callback of another function, so that return affects the return value of the callback to $.get
You want to use callbacks. So,
function checkLoginStatus(callback) {
$.get("func.php", {
op: 'login_status',
r: Math.random()
}, function(data) {
if (data == "Yes") {
showSalesView();
callback(true);
} else {
loginView();
callback(false);
}
});
}
and then
checkLoginStatus(function(result) {
alert(result);
});
The AJAX call is asynchronous, so the function that you specify as callback will be executed when the response arrives. The code doesn't wait for the response to exit from the checkLoginStatus function.
You can use a callback method to display the result:
function checkLoginStatus(callback) {
$.get("func.php", {op:'login_status', r:Math.random()}, function(data) {
if (data == "Yes") {
showSalesView();
callback(true);
} else {
loginView();
callback(false);
}
});
}
checkLoginStatus(function(status){ alert(status); });
what you are seeing is the undefined (void) return from the .get() function,
notice carefully that .get function call contains another function as the third parameter ( first being the url, second being an anon object) that is the "callback" for the results of the .get function, this is called later when the results have been returned from the server.
The returned bool is being returned by the $.get functions callback, not checkLoginStatus.
function checkLoginStatus() {
$.get("func.php", {op:'login_status', r:Math.random()},
// Start Callback Function
function(data) {
if (data == "Yes") {
showSalesView();
return true;
} else {
loginView();
return false;
}
// End Callback Function
});
}