Node, RSVP.js array of promises [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
i can get the RSVP array of promises to work:
//if user wants to change username
var promises = [];
promises['username'] = new RSVP.Promise(function(resolve, reject){
if(user.username !== session.username){
//check if username is available
$model_users.getBy({
what:'id',
where: " username = "+db.escape(user.username) +" AND id != "+ db.escape(session.id_user)
})
.then(function(results){
if(!results || results.length <= 0){
//update username is available
$model_users.update({
update:{username: db.escape(user.username)},
where: " id = "+ db.escape(session.id_user)
})
.then(function(success){
confirm.username = 'was_saved';
resolve(success);
},function(err){
reject(err);
console.log('db-error 55299 ' + err);
res.send('db-error');
});
}else{
validation.username = 'error_username_exists';
resolve(validation);
res.send({"validation":validation});
}
},function(err){
reject(err);
console.log('db-error 0299 ' + err);
res.send('db-error');
});
}else{
reject('no username to update - is same to session username');
}
}
//create new JWT and send it back to FE localSTorage
RSVP.all(promises).then(function(){
$model_users.getBy({
what:'id , username',
where: " id = "+ db.escape(session.id_user)
}).then(function(results){
if(results && results.length > 0){
//set new user session and token
var auth = {};
auth.username = results[0].username;
auth.id_user = results[0].id;
auth.session_token = jwt.sign(auth, config.session_secret_key, { expiresInMinutes: config.session_expiration });
res.send({"auth":auth,"confirm":confirm});
}else{
res.send('db-error');
}
},function(err){
console.log('db-error 0.577 '+ err);
});
});
the error returned is:
RSVP.all(promises).then(function(){
^^^^
SyntaxError: Unexpected identifier
How is his possible? i'm following the official doc https://github.com/tildeio/rsvp.js/#arrays-of-promises
I setted it on top of node app.js :
var RSVP = require('rsvp');

You're missing a ) two lines above RSVP.all(promises)....
Consider using a linter, which will catch this sort of error immediately. See e.g. SublimeLinter.

Related

Function return value undefined [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I have this function:
function addressVerification() {
var del;
let addVer = $('#add_verified').val();
let maddVer = $('#madd_verified').val();
if (addVer == "yes" && maddVer == "yes") {
del = true;
} else {
del = false;
}
return del;
}
When I call it:
$('#add_verified').change(function(){
var ver = addressVerification();
console.info("This is the returned value from the verified address function: "+ ver);
});
It comes back as "undefined."
What am I doing wrong?
You have a syntax error
function addressVerification() {
var del;
let addVer = $('#add_verified').val();
let maddVer = $('#madd_verified').val();
if (addVer == "yes" && maddVer == "yes") {
del = true;
} else {
del = false;
}
} . <----- This is closing the function, ant thus, returning undefined
return del;
}

Discord bot Error Javascript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Do anyone know the problem at this javascript bot?
The window (Start.bat) just open and close. Main error is at line 100 - 115!
I use it on my discord server and i need a bot to ban words. The bot is edited to ban words, but now it don't work. (Line 100 - 115)
I hope someone knows the problem.
It is made for a bot named The parrot, and i need a working code.
Code:
const Discord = require('discord.js');
const bot = new Discord.Client();
var fs = require("fs");
var oldAuthor;
// ADD YOUR BOT'S TOKEN HERE
const token = " *censored* ";
bot.on('ready', () => {
});
bot.on('message', message => {
// Makes sure the first word is ~createcommand
var checkMessage = message.content.split(" ");
if(checkMessage[0] == "~lagkommando")
{
// commandText gets grabbed by splitting the string with |
// commandName gets grabbed by splitting the string with spaces
// command Name must have '~' in it just so you can't use any word you
// want
var commandText = message.content.split("|",2);
var commandName = message.content.split(" ");
if(commandName[1].charAt(0) == "~")
{
checkExistingCommand(commandText,commandName);
message.channel.sendMessage("Command " + commandName[1] + " has been created");
} else {
message.channel.sendMessage("Command must contain '~'");
}
}
/*
* Checks the commands.txt file to see if anyone posted the command.
* commands.txt is split with semi-colons. For loop to check every single
* command. If there is a match, then it opens up the txt file associate
* with that command. If there are multiple pictures then the user should
* type $random{} and then type in all the pictures in the brackets
* separated by semi-colons. If there is no $random{} then it just sends the
* message.
*/
fs.readFile('./commands/commands.txt','utf8',function(err,f){
var com = f.toString().split(";");
for(i = 0; i < com.length; i++)
{
if(message.content == com[i])
{
if(com[i] == "~commands")
{
message.channel.sendMessage(com);
break;
}
if(com[i] == "~help")
{
message.channel.sendMessage("Kommandoer: ~help, ~commands, ~database, ~Hei, ~memes og ~problem");
break;
}
var command = "./commands/" + com[i] + ".txt";
fs.readFile(command,'utf8', function(err,f){
try{
var com2 = f.toString().split(";");
var num = Math.random() * ((com2.length - 1) - 0) + 0;
message.channel.sendMessage(com2[Math.floor(num)]);
}
catch(err) {
console.error("",err);
}
});
}
}
});
});
function checkExistingCommand(commandText,commandName)
{
var com = commandName[1];
var desc = commandText[1];
var CE = false;
fs.readFile('./commands/commands.txt','utf8',function(err,f){
var findCommands = f.toString().split(";");
for(i = 0; i < findCommands.length; i++)
{
if(com == findCommands[i])
{
CE = true;
}
}
if(CE == true)
{
createCommand(desc,true,com);
} else if (CE == false)
{
createCommand(desc,false,com);
}
});
}
bot.on('message', message => {
var sender = message.author;
var msg = message.content.toUpperCase();
var prefix = '>'
if (sender.id === ' *Censored* ') {
return;
}
if (msg.includes('noob')) {
message.delete();
message.author.send('The word noob is banned, next time YOU can be banned! ')
}
}
// Appends and/or creates the text files.
function createCommand(desc,b,com)
{
var fileName = "./commands/" + com + ".txt";
if(b == true)
{
fs.writeFile(fileName,desc,function(err){
if(err) {
return console.error(err);
}
});
} else if (b == false){
fs.appendFile('./commands/commands.txt',com+';',(err) =>
{
if(err) throw err;
});
fs.writeFile(fileName,desc,function(err){
if(err) {
return console.error(err);
}
});
}
return;
}
bot.login(token);
I see that you need a better text editor.
On Line 115. (At the eventhandler for message recieved for your Client). You were missing your closing line of );.
Also, just in case you did not knew, I realised that you made your msg string variable to upper-case before you compared it to a lower-cased string for commands. Do note that includes() method is case-sensitive.
I am using Visual Studio Code for my text editor. If somehow it does not show you syntax highlighting and stuff, check the bottom right of the editor, it should display Javascript there.
If it does not, change it to Javascript and it should show the syntax highlighting and stuff correctly.

TypeError: Cannot read property 'on' of undefined in firebase api [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I am creating a simple chat application using firebase javascript api.
Here is the work flow
1.when user A wants to chat with user B first create a unique chat id
2.create a unique firebase url for these two users and user messages are stored into this.
3.display the chat messages in chat window.
Here is the code abve steps
.controller('chatCtrl',function($scope,$stateParams,$http){
var messagesRef;
/*--create a unique chat-id for two users--*/ $http.get(url+'getchatid&&sender='+sender+'&&recevier='+receiver).success(function(data){
if(data=='error'){
alert("Error in connection try again");
}else{
//create unique firebase-url for these two users
messagesRef= new Firebase(chaturl+data);
}
});
/*---display the messages in chat window--*/
messagesRef.on('value', function (snapshot) {
var msg= snapshot.val();
if(msg!=null){
$scope.messages=msg;
}else{
$scope.messages='';
}
});
/*--add chat messages--*/
$scope.sendmessage=function(user){
if(!user||!user.message){
alert("Message required");
}else{
messagesRef.push({text:user.message});
user.message='';
}
}
});
Problem is i cant implement the step-3,step-1 and 2 is works fine.
When trying to display the messages i will get the following error
TypeError: Cannot read property 'on' of undefined
I think problem is associated with this code
messagesRef.on('value', function (snapshot) {
var msg= snapshot.val();
if(msg!=null){
$scope.messages=msg;
}else{
$scope.messages='';
}
});
Modified your code
controller('chatCtrl', function ($scope, $stateParams, $http) {
var messagesRef;
$http.get(url + 'getchatid&&sender=' + sender + '&&recevier=' + receiver).success(function (data) {
if (data === 'error') {
alert("Error in connection try again");
} else {
messagesRef = new Firebase(chaturl + data);
messagesRef.on('value', function (snapshot) {
var msg = snapshot.val();
if (msg !== null) {
$scope.messages = msg;
} else {
$scope.messages = '';
}
$scope.$apply();
});
}
});
$scope.sendmessage = function (user) {
if (!user || !user.message) {
alert("Message required");
} else if (messagesRef) {
messagesRef.push({text: user.message});
user.message = '';
}
};
});

How do I process an element before moving on to the next one in a for each loop?

var prompt = ...
var connection = ...
prompt.start();
var property = {
name: 'yesno',
message: 'approve this screencast?',
validator: /y[es]*|n[o]?/,
warning: 'Must respond yes or no',
default: 'no'
};
connection.queryAsync('SELECT * FROM screencasts WHERE approved = 0')
.spread(function(screencasts) {
screencasts.forEach(function(screencast) {
console.log('Title: "' + screencast.title + '".');
prompt.get(property, function(err, res) {
console.log('Command-line input received:');
console.log(' result: ' + res.yesno);
});
});
});
Aim: To enumerate the screencasts and prompt the user to approve or deny them, interactively.
Problem: I think the problem is that, the loop does not block at all, resulting in the next element being processed too quickly:
How do I wait for the user to input a value before "processing" the next element in the sequence?
Someone mentioned mapSeries, and that got me thinking about the example that shows how to avoid mapSeries and instead use bluebird's map.
What I ended up with is this:
var promise = ...
var prompt = ...
var connection = ...
promise.promisifyAll(prompt);
...
connection.queryAsync('SELECT * FROM screencasts WHERE approved = 0')
.spread(function(screencasts) {
var current = promise.resolve();
promise.map(screencasts, function(screencast) {
current = current.then(function() {
console.log('Title: "' + screencast.title + '".');
return prompt.getAsync(property);
}).then(function(res) {
console.log(res);
});
return current;
});
});
It seems to work well. I am curious, though. Is map the most appropiate function for this?

node js callback function

I am new to nodeJs. In my code I have a asynchronous function for finding records from mongoDB.
var restify = require('restify');
var mongojs = require('mongojs');
var ip_addr = '127.0.0.1';
var port = '8080';
var server = restify.createServer({
name : "signapp"
});
server.use(restify.queryParser());
server.use(restify.bodyParser());
server.use(restify.CORS());
var connection_string = '127.0.0.1:27017/signapp';
var db = mongojs(connection_string, ['signapp']);
var docDetails = db.collection("SIGN_DOCUMENT_DETAILS");
var PATH = '/documents'
server.post({path : PATH + '/:search', version: '0.0.1'}, searchDoc);
function searchDoc(req, res, next)
{
var criteria = {};
criteria.DOC_NAME = req.params.DOC_NAME;
if (criteria.DOC_NAME !== '' || criteria.DOC_NAME !== null)
{
docDetails.find({DOC_NAME : criteria.DOC_NAME}, function(err, users){
if( err || !users){
console.log("No record found");
}
else {
console.log('record found');
}
});
}
}
In my request I pass a string parameter. I am getting 'record found' response in my console when the condition is matched.
But the problem is I am getting response in console as 'record found' even when the find condition fails. I tried a lot ti find a solution but failed.
Please tell me where I went wrong in my code. A solution for this bug will be greatly appreciated. Thanks in advance.
change your condition like
if( err){
console.log("An error occurred");
} else if(!users || users.length==0) {
console.log("No results found");
} else {
console.log('record found');
}
You need to add a condition to check if the returned array was empty.
note :
javascript empty array seems to be true and false at the same time gives a proper explanation on why u should not use if(!users) to check if the array was empty.

Categories

Resources