Cannot read property 'finally' of undefined - javascript

I can't figure out why I'm getting an
Cannot read property 'finally' of undefined error here..
$scope.saveToDos = function(){
console.log("Save to do was pressed.")
var filteredTodos = $scope.todos.filter(function(todo){
if(todo.edited){
return todo
}
})
console.log("There are " + filteredTodos.length + " edited todos")
dataService.saveToDos(filteredTodos)
.finally($scope.resetTodoState())
}
It errors out on the finally line and I'm not sure why.
The issue can be reproduced cloning Git repo
https://github.com/Velua/To-Do-List
this.saveToDos = function(todos){
var queue = [];
todos.forEach(function(todo){
var request;
if(!todo._id){
request = $http.post('/api/todos', todo);
} else{
request = $http.put('/api/todos/' + todo._id, todo).then(function(result){
todo = result.data.todo;
return todo
})
}
queue.push(request);
})
$q.all(queue).then(function(results){
console.log("I saved " + todos.length + " todos!");
})
}
Thanks!

You aren't returning anything from saveToDos(), so the return value is by default undefined.
You probably wanted to return $q.all(...

Related

branch.io Share Sheet message

This is a function im calling on Ionic
regularShare(){
// only canonicalIdentifier is required
var properties = {
canonicalIdentifier: 'content/' + this.itemId
}
// create a branchUniversalObj variable to reference with other Branch methods
var branchUniversalObj = null
Branch.createBranchUniversalObject(properties).then(function (res) {
branchUniversalObj = res
// optional fields
var analytics = {
}
// optional fields
var properties = {
}
var message = 'Check out this link'
// optional listeners (must be called before showShareSheet)
branchUniversalObj.onShareSheetLaunched(function (res) {
// android only
console.log(res)
})
branchUniversalObj.onShareSheetDismissed(function (res) {
console.log(res)
})
branchUniversalObj.onLinkShareResponse(function (res) {
console.log(res)
})
branchUniversalObj.onChannelSelected(function (res) {
// android only
console.log(res)
})
// share sheet
branchUniversalObj.showShareSheet(analytics, properties, message)
});
}
When I change var message to the following, it errors out. Error below.
var message = "Check out " + this.itemDetails.name + " (" + this.itemDetails.subcat+ ") in " + this.itemDetails.location + "."+ " Address: " + this.itemDetails.address+ ". Contact: " + this.itemDetails.phone
ERROR: ERROR Error: Uncaught (in promise): TypeError: undefined is not an object (evaluating 'this.itemDetails')
However, in all my other functions it seems to run fine using the same message and variables.
Just trying to place the value of the variables within the message instead of the default message: Check out this link
Thanks :)
To get it working, I had to change the line from
Branch.createBranchUniversalObject(properties).then(function (res) {
To
Branch.createBranchUniversalObject(properties).then((res) => {

variable is not getting defined even though the code works somwhere else

so i am building a game in three js and trying to make it multiplayer throught socket.io so i am loading all of my characters into an array called players on my server side
and then i pass it to each client when they connect like so
socket.on('addPlayer', function(username) {
players.push(username)
console.log(username + " joined")
console.log("online Users " + players)
socket.broadcast.emit('syncPlayers', players)
socket.emit('syncPlayers', players)
})
and on my client syncPlayers looks like this
socket.on('syncPlayers', function(players) {
players.forEach(function(value) {
if (value == username) {
console.log("not adding " + value + " thats you ")
loadPlayerdata(username)
} else {
console.log("player Online " + value);
newplayer = value;
loadPlayerdata(newplayer)
addPlayer(newplayer)
}
});
})
then it calls this wich sends the server data
function loadPlayerdata(playerName) {
console.log(playerName)
console.log("phase1")
socket.emit('loadPlayerdata', playerName)
}
then this is called and it retrieved the player name and the data of the players location this is were my problem lies
socket.on('loadPlayerdata', function(data, username) {
toMove = threeObjects[username + "Char"]
if (data == "null" || "") {
console.log(username + " is new")
} else {
console.log(username + " Exists")
console.log(toMove)
toMove.position.set(world.spawnPointx, world.spawnPointy, world.spawnPointz)
}
i keep getting Uncaught TypeError: Cannot read property 'position' of undefined
even though i can use this
function addPlayer(playerName) {
var charObjectName = playerName + "Char"
var threeObject = models.tent1.mesh.clone();
scene.add(threeObject)
//threeObject.position.set(world.spawnPointx, world.spawnPointy, world.spawnPointz)
// set reference
threeObjects[charObjectName] = threeObject;
}
btw i have an object
var threeObjects = {};
can someone please explain why it wont work and how to fix it
You can read this answer to understand the difference between dot and brackets notation.
You are getting error because, tomove seems to be undefined and dot notation will throw error if any new user joins and if the object is empty.
Check if this helps. This will assign the object key as username and position as an value which will be array like this,
{"usernamechar": {"position": [x,y,z]}}
socket.on('loadPlayerdata', function(data, username) {
if (data == "null" || "") {
console.log(username + " is new")
} else {
console.log(username + " Exists")
threeObjects[username + "Char"]["position"] = [world.spawnPointx, world.spawnPointy, world.spawnPointz]
}
}

javascript post not doing function but load url

I am creating Stratego.
(the error is farther down)
so i am creating the map when the page is loadet whit:
turn = true;
komboType = "2kombo";
GameOpsetning = [];
GameOpsetningEnemy = [];
$(document).ready(function() {
createmap();
}
and then i do some console log to make sure it works..
function createmap () {
if (!GameStarted) {
console.log("GameOpsetning" + GameOpsetning);
if(GetSetup(Gameid)){
console.log("GameOpsetning1" + GameOpsetning);
}
else
{
console.log("GetSetup : error");
}
and here the error comes, it will open the file "game.php" whit no error. but it will not do eny thing in side the post/funcion. It will not do the alert or the if or console.log?
function GetSetup (Gameid) {
console.log("GameOpsetning3: " + GameOpsetning);
if ($.post("game.php", { gameid: Gameid }, function(data) {
alert(data);
var data2 = JSON.stringify(data);
alert(data2);
//var json = $.parseJSON(data);
if (data2.status2 && data2.status2 != "false") {
console.log("data.game: " + JSON.stringify(data.game));
GameOpsetning = JSON.stringify(data.game);
GameOpsetningEnemy = JSON.stringify(data.enemygame);
komboType = data.type;
turn = data.turn;
console.log("GameOpsetning5: " + GameOpsetning);
return true;
}
else
{
console.log("error: ");
return false;
}
})){
console.log("post: done");
}else{
console.log("post: error");
}
console.log("GameOpsetning4: " + GameOpsetning);
}
the console output:
GameOpsetning
GameOpsetning3:
post: done
GameOpsetning4:
GetSetup : error
there is no console errors and the page is return JSON
and it have try ed to do like:
console.log("GameOpsetning" + GameOpsetning);
GetSetup(Gameid);
console.log("GameOpsetning1" + GameOpsetning);
if (CheckGame()) {
then the console log is:
GameOpsetning
GameOpsetning1
GameOpsetning3:
post: done
GameOpsetning4:
GetSetup : error
Sorry for my bad English.
You're testing if($.post("game.php",... What is the result of this if test? Always true. Because anything that is not false, 0 or undefined is true. You're not testing the result of an ajax call, you're testing an ajax call (a function).
Same with if(GetSetup(Gameid)). GetSetup(Gameid) returns : console.log("GameOpsetning4: " + GameOpsetning). if(GetSetup(Gameid)) result is undefined, which explains the GetSetup : error output.
Type this in your console : if(console.log('test')) alert("yay") : it won't alert "yay", it will just log 'test' and return undefined. This is your if(GetSetup(Gameid)).
Same way, if you type if($.post("game.php")) alert('yay'), it will alert yay, because the test is always true, whatever the result of the $.post.

Javascript, why would "this" be undefined in a bound node callback?

I'm encountering this error for the first time and I'm at a loss of what could cause it.
AccountController.create = function () {
var password = this.param('password'),
confirmPassword = this.param('confirmPassword'),
account = new Account(),
errorMessage = "",
errors = "",
error,
errorCount;
if (password !== confirmPassword) {
this.req.flash('warning', 'passwords do not match');
return this.redirect(this.urlFor({action: 'index'}));
}
account.email = this.param('email');
account.set('password', password);
account.name.first = this.param('name.first');
account.name.last = this.param('name.last');
account.access = this.param('access');
account.save(function (err, account, numberAffected) {
if (err) {
console.log("THIS: " + this);
errorMessage = "";
errors = err.errors;
if (!errors) {
errors = [{message: "There is already an account with this email address."}];
}
errorCount = errors.length;
for (error = 0; error < errorCount; error = error + 1) {
if (typeof errors[error] === "string") {
errorMessage += errors[error].message + " ";
}
}
this.req.flash('warning', errorMessage);
return this.redirect(this.urlFor({action: 'index'}));
}
return this.redirect(this.urlFor({controller: "profile", action: 'login'}));
}).bind(this);
};
I'm hoping that there's no additional code required to make the example work.
Console output (running via nodemon) looks like this:
THIS: undefined
/Users/crispensmith/Documents/cinchedStore/Site/app/controllers/account_controller.js:68
this.req.flash('warning', errorMessage);
^
TypeError: Cannot read property 'req' of undefined
You're doing .bind(this) on the return value of account.save, not the function you're passing into it. Just move the bind inside the bracket;
account.save((function // ... possibly also use an extra parenthesis
// ...
}).bind(this)); // to make the bind target more obvious?

Firefox not catching "undefined" error in javascript

I have some javascript code which calls a servlet with parameters based on the selected option from a SELECT list. It is possible that there will be no options in the selectCampaigns(account) so there is a try and catch.
The code in the catch should be called if,
var selectedCampaign = selectCampaigns.options[selectCampaigns.selectedIndex].text;
fails. This works in both chrome and IE but in firefox it gives a TypeErrror,
TypeError: selectCampaigns.options[selectCampaigns.selectedIndex] is undefined
which does not trigger the catch. May I have some suggestions on how to handle this? (in addition firefox does not show any of the alerts that I have inserted for debugging).
function selectcampaign(account) {
alert('alert1');
var selectCampaigns = document.getElementById("campaignSelect");
var urlstrg = "http://localhost:8080/SalesPoliticalMapping/OrgChart";
try {
var selectedCampaign = selectCampaigns.options[selectCampaigns.selectedIndex].text;
urlstrg = "http://localhost:8080/SalesPoliticalMapping/OrgChart?account=" + account + "&campaign=" + selectedCampaign;
} catch(err) {
alert(err);
urlstrg = "http://localhost:8080/SalesPoliticalMapping/OrgChart?account=" + account;
} finally {
window.location.href = urlstrg;
}
};
You should better test the value instead of dealing with errors.
function selectcampaign(account) {
var selectCampaigns = document.getElementById("campaignSelect");
var urlstrg = "http://localhost:8080/SalesPoliticalMapping/OrgChart?account=" + account;
if(selectCampaigns.options[selectCampaigns.selectedIndex]) {
urlstrg += "&campaign=" + selectCampaigns.options[selectCampaigns.selectedIndex].text;
}
window.location.href = urlstrg;
};

Categories

Resources