I've created a function into backbone view that return true or false under some condition.
The issue is that the return value is evere undefined. I think it is a scope problem.
This issue is different from Ajax return because my return is inside an iteration and not in an ajx call. The previous Ajax call in my code is sync and not async.The console.log inside my iteration is correctly printed, only return statement seems doesn't work.
isAlreadyRegistered: function(){
this.checkUser = new Utenti();
this.checkUser.fetch({async:false});
_.each(this.checkUser.models, function (user) {
if(user.get("idTwitter") === this.utente.get('idTwitter')){
console.log("gia reg");
return true;
} else {
console.log("non reg");
return false;
}
}, this);
}
console.log(isAlreadyRegistered());//ever undefined
You don't want to use each, but every or some. They will return booleans depending on what your callback invocations did return.
isAlreadyRegistered: function(){
this.checkUser = new Utenti();
this.checkUser.fetch({async:false});
var id = this.utente.get('idTwitter');
return _.some(this.checkUser.models, function (user) {
return user.get("idTwitter") === id;
});
}
Related
I am new to angular and I am working on a project in my company where I have to implement a delete function.
I have manage to implement the function where user goes ahead with the deletion. But if he changes his mind in the last minute and cancel the delete confirmation, I am getting an error.
Here is my code:
$scope.deleteButtonClick = function () {
if ($scope.hasRemove()) {
$scope.deleting = true;
//Fetch the promise and add our own state management to it
var promise = $scope.removeAction(); // this remove action calls the below 'remove' function
if (!promise.then) {
throw "Wizard's bound 'deleteAction' must return a closure."
}
promise.then(function () {
$scope.deleting = false;
}, function () {
$scope.deleting = false;
});
}
};
Following is the remove function where I want to return a closure.
$scope.remove = function () {
if (confirm("Confirm Delete?")){
var data = {};
data.id = EventService.event.id;
// delete
return $http.post('/admin/deleteAjax/', data).then(
function (response) {
if (response.data.status == 'success') {
RegistryService.getItem("successModal").show();
setTimeout(()=>{
location.replace("/admin/index")
}, 2000);
}
else if (response.data.status == 'error'){
RegistryService.getItem("errorModal").show();
}
}
);
}
else {
// This is where I need to return a closure
// when user presses 'cancel' button how can I return a closure or skip the error?
}
};
Following is the error I am getting when I return false in the else section.
Wizard's bound 'deleteAction' must return a closure. undefined
Does anyone have an idea how to fix this issue?
The problem is that $scope.remove() needs to return a Promise, and the else clause in the confirm() block is not returning a Promise.
To do that, you can use the AngularJS $q service to create a Promise and return it.
So your else block would look like this:
} else {
// This is where I need to return a closure
// when user presses 'cancel' button how can I return a closure or skip the error?
const deferred = $q.defer(); // <------------ use $q service to create a deferred
deferred.resolve({ cancelled: true }); // <-- resolve it to whatever value you want
return deferred.promise; // <---------------- and return its promise
}
Here's a fiddle showing this approach.
I call a function "returnsTrue" which calls itself when parameter "redo" is set to true. Then I recall the same function "returnsTrue" with parameter "redo" set to false and I want to return true. But in fact I only get "undefined" back.
I can't really understand what is going on here:
function returnsTrue(redo){
if(redo){
console.log('Restart Function');
returnsTrue(false);
}else{
console.log('It returns true');
return true;
}
}
if(returnsTrue(true)){
console.log('1');
}else{
console.log('2');
}
var isTrue = returnsTrue(true);
console.log(isTrue);
// is undefined
Check https://jsfiddle.net/8820r2ug/
There are two branches to the if statement.
Only one of those two branches includes a return statement.
If it hits the if (and not the else) then there is no return statement and it returns undefined.
You need to add a return statement to the if side of the if/else.
So what's happening is the assignment call isn't returning a value, it's the call within the function that's returning true, so your assignment ends up undefined, try returning the function call within the function like so:
function returnsTrue(redo){
if(redo){
console.log('Restart Function');
return returnsTrue(false);
}else{
console.log('It returns true');
return true;
}
}
if(returnsTrue(true)){
console.log('1');
}else{
console.log('2');
}
var isTrue = returnsTrue(true);
console.log(isTrue);
// is undefined
I've gotta be missing something obvious, but I can't figure it out and it's driving me crazy. I'm using angular and I have a factory 'Auth' which has this function in the return { } of 'Auth' (forced to return false for emphasis):
isAuthenticated: function() {
var storedJwt = $window.sessionStorage.authToken;
console.log('stored JWT: '+storedJwt);
if(storedJwt){
var storedPayload = jwtHelper.decodeToken(storedJwt);
console.log('payload: '+JSON.stringify(storedPayload));
if(jwtHelper.isTokenExpired(storedJwt)){
console.log('is expired expired: '+jwtHelper.getTokenExpirationDate(storedJwt));
delete $window.sessionStorage.authToken;
} else {
console.log('is not expired expires: '+jwtHelper.getTokenExpirationDate(storedJwt));
}
}
return false;
//LocalService.get('authToken');
},
Then in a controller I'm doing this:
$scope.isLoggedIn = function(){
console.log('chk:'+Auth.isAuthenticated);
return Auth.isAuthenticated;
};
the console.log though is showing: http://grab.by/GZSw
And so always returns true. Why can't I get it to be false? I think this is probably very basic js issue, but I don't get it.
You need to invoke the function with parens.
$scope.isLoggedIn = function(){
console.log('chk:'+Auth.isAuthenticated());
return Auth.isAuthenticated();
};
Auth.isAuthenticated is a reference to the function. It is not calling the function.
Therefore, it will always be truthy and never calls the function either. It is simply an object now.
If you want the return a value from inside the function you need to call it:
return Auth.isAuthenticated();
That being said, there are conditions in the function that don’t return anything and the function itself never returns true inside.
Here in result() method, whenever it comes to else part, I need to get out of the function callthis().
It should not execute kumar() function.
Is this possible?
Actually, I can use like this
if(result) //if this method is true, it will come inside
{
kumar();
}
But this is not I want. while returning false from result() method, it should get out of the loop function calthis()
function calthis()
{
var i=1;
if(i==0)
{
alert("inside if");
}
else
{
alert("inside else");
result();
kumar();
}
}
function result()
{
var res = confirm("are you wish to continue");
if(res==true)
{
return true;
alert("inside if result");
}
else
{
return false;
}
}
function kumar()
{
alert("inside kumar");
}
Click here
There's a bunch wrong here.
First, if (result) just tests whether the variable result contains a truthy value, it doesn't actually invoke the function. If you want to test the return value of the function, you need
if (result()) {
Secondly, you're not understanding that return immediately leaves the current function. You can't meaningfully do this:
if(res==true)
{
return true;
alert("inside if result");
}
That alert cannot be reached. The function returns immediately when return true is encountered.
Thirdly, to exit callThis early, you simply need to return early. It's up to the function callThis to conditionally return; you cannot force a return from down inside the result function. A function cannot forcibly return out if the context that called it. It's not up to the internals of the result function to determine if kumar should run. You cannot influence the path of execution in the calling method directly. All result can do is return something, or (needlessly complex in this case) accept a callback and conditionally execute it.
Just return from callThis if the result of result() is false:
function calthis()
{
var i=1;
if(i==0)
{
alert("inside if");
}
else
{
alert("inside else");
if (!result()) return;
kumar();
}
}
To exit any function simply use return;
However it seems like you want to call a function if the user clicks confirm, is that correct? If so:
var res = confirm("are you wish to continue");
if (res === true)
{
kumar();
}
If you want to call a function if the user does not click confirm:
var res = confirm("are you wish to continue");
if (!res)
{
kumar();
}
You got a lot of confusing code going on there, but if the idea is to stop a function, simply use "return false;" and the code execution stops
In my case I have one repository like this from temphire (breeze)
define(['durandal/system'], function (system) {
var Repository = (function () {
var repository = function (entityManagerProvider, entityTypeName, resourceName, fetchStrategy) {
.........
this.find = function (predicate) {
var query = breeze.EntityQuery
.from(resourceName)
.where(predicate);
return executeQuery(query);
};
function executeQuery(query) {
return entityManagerProvider.manager()
.executeQuery(query.using(fetchStrategy || breeze.FetchStrategy.FromServer))
.then(function (data) { return data.results; });
}
................
};
return repository;
})();
return {
create: create,
getCtor: Repository
};
function create(entityManagerProvider, entityTypeName, resourceName, fetchStrategy) {
return new Repository(entityManagerProvider, entityTypeName, resourceName, fetchStrategy);
}
});
NOW
HOW CAN DO LIKE SOME THIS
repository.query(predicate).execute();
function query(predicate) {
return query = breeze.EntityQuery
.from(resourceName)
.where(predicate);
};
function executeQuery(query) {
return entityManagerProvider.manager().executeQuery(query.using(fetchStrategy || breeze.FetchStrategy.FromServer)).then(function(data) {
return data.results;
});
}
function execute() -- >
return executeQuery
the first action return query and after to execute
many thanks
I think the problem with what you are trying is that return terminates execution. If you want to do something as well as return in that function, then you need to do it before you return.
If, on the other hand, you really need to return the value and then execute something, then you should have the method that calls the function expecting the return, call the function to get the return value, and then have that calling function execute the thing you want executed. If that execution needs some data from the function that returns the value, then return that information with the value returned, and pass it into the function that does the execution.
Use
executeQueryLocally // This is syn
instead of
executeQuery // This is async
executeQuery sync