I am trying to query the user twice (more than once in general), but everything gets printed out together and the first response get processed by both functions. I believe this has to do with the asynchronous nature of node.js. Can you please point me towards module that would take care of this for me or an implementation in prompt module? Thank you.
var prompt = require('prompt');
prompt.start();
console.log("Enter a number: ");
prompt.get(['number'], function(err, result) {
if (!isNaN(result.number)) {
console.log("You entered a number.");
} else {
console.log("You did not enter a number.");
}
});
var prompt2 = require('prompt');
prompt2.start();
console.log("Enter a number again: ");
prompt2.get(['number1', 'number2'], function(err, result) {
if (Number(result.number1) > Number(result.number2))
console.log("The first input is bigger");
else if (Number(result.number1) == Number(result.number2))
console.log("Both inputs are equal");
else
console.log("The second input is bigger");
});
I am not sure if you actually need both prompt instances. I think you can achieve what you want with only one prompt and just calling get second time within the first get's callback.
var prompt = require('prompt');
prompt.start();
console.log("Enter a number: ");
prompt.get(['number'], function(err, result) {
if (!isNaN(result.number)) {
console.log("You entered a number.");
} else {
console.log("You did not enter a number.");
}
console.log("Enter a number again: ");
prompt.get(['number'], function(err, result) {
if (result.number < 20)
console.log("small");
else if (result.number < 50)
console.log("medium");
else
console.log("large");
});
});
Related
I've developed a simple login system in JS. When the password, the username or both are incorrect it's suposed to show an alert but now it shows 4. I know it is because of the for loop but I don't know how to get rid of it without breaking all the code. Thanks in advance =)
I leave here the piece of code:
function getName() {
var user = document.getElementById('Username').value;
var pass = document.getElementById('Password').value;
for (let f = 0; f < arr.length; f++) {
if (user == arr[f][0] && pass == arr[f][1]) {
document.write("Welcome back ", user, ", we've missed you");
}
if (user == arr[f][0] && pass != arr[f][0]) {
alert("Your password is incorrect");
}
else if (user != arr[f][0] && pass == arr[f][1]) {
alert("Your username is incorrect");
}
else {
alert("Unnexistant account");
}
}
}
Add break; after each document.write or alert statements.
Your instinct is correct, and a for loop is probably not ideal here. It is hard to read and debug and it's also kind of ugly. If you want to stick with it, the other answers show you how.
Assuming arr is an array of usernames & passwords, you can convert this into a Map and remove your loop completely.
const map = new Map();
arr.map(e => m.set(e[0], e[1]));
try {
if (map.get(user) === pass) {
document.write("welcome back " + user + ", we missed you.");
} else {
// although this might be too much info from a security standpoint.
document.write("incorrect password");
}
} catch (e) {
document.write("could not find user.");
}
If the username for one account is wrong, you don't want to tell them their account doesn't exist until you check it for every single account:
function getName() {
var user = document.getElementById('Username').value;
var pass = document.getElementById('Password').value;
for (let f = 0; f < arr.length; f++) {
if (user == arr[f][0] && pass == arr[f][1]) {
document.write("Welcome back ", user, ", we've missed you");
return; // exit from the function since we've found an account
}
if (user == arr[f][0] && pass != arr[f][0]) {
alert("Your password is incorrect");
return; // exit from the function since we've found a username match
}
}
// couldn't find match, alert
alert("Your account does not exist.");
}
I'm working on a node word guessing game and I'm trying to have code that prompts the user for input until they run out of guesses or get the word right. Right now I'm having an issue working with prompt's callback. Because of the nature of callbacks my code runs through all the "prompt" code for each word before finally waiting for user input. I've tried using a forEach and while loop originally. Later tried setting up promises, but I haven't figured anything out.
for(i = 0; i < wordsInPlay.length; i++){
if(losses < 3){
let solved = false;
wordThisRound = new Word(wordsInPlay[i]);
wordThisRound.setupWord();
getGuess();
}
}
Here's the getGuess function implements the prompt nod.js package:
function getGuess() {
wordThisRound.updateWordDisplay();
if (wrongsLeft > 0) {
new Promise(function(resolve) {
prompt.get(guessObject, function(err, result) {
console.log('line 68');
if(err) throw err;
let userGuess;
const letterGuessed = result.guess.toLowerCase();
if (wordThisRound.wordObject.hasOwnProperty(letterGuessed) && wordThisRound.wordObject[letterGuessed].guessed === false) {
userGuess = true;
wordThisRound.wordObject[letterGuessed].guessed = true;
wordThisRound.wordObject[letterGuessed].changeDisplay();
}
else {
userGuess = false;
wrongsLeft--;
}
resolve({gussedRight: userGuess, letter: letterGuessed});
});
}).then(function(promise){
console.log('Inside .then function.');
new Promise(function(resolve){
gameFeedback(promise.gussedRight, promise.letter);
resolve();
});
}).then(function(){
getGuess();
});
}
else console.log("You're our of wrong guesses...You lost this round.");
}
I have been on this for a good few hours.
I have the below function which reads from a table in my postgres db. It works as expected if there is stored strings in a column.
I can't get the 'else if' statement to work when there is no string in a field. To test this out I have a completely empty column under brand_code and its still executing the 'else' statement.
Now, I know why. There are 3 rows in the table. When I change the else if to === 3, it works as I'd like.
What code do I need to make the 'else if' statement work if the field is empty? (I plan to expand the SELECT statement later).
readCodes: function(callback) {
var pool = new pg.Pool(config.PG_CONFIG);
pool.connect(function(err, client, done) {
if (err) {
return console.error('Error acquiring client', err.stack);
}
client
.query(
'SELECT brand_code FROM public.voucher_codes',
function(err, result) {
if (err) {
console.log(err);
callback('');
} else if (result.rows.length === 0 ) {
console.log(result);
callback('');
} else {
let codes = [];
for (let i = 0; i < result.rows.length; i++) {
codes.push(result.rows[i]['brand_code']);
}
callback(codes);
};
});
});
}
}
Really struggled with this all day so any help is appreciated.
I am still learning. Prior to last week, I have never coded so apologies if this is amateur hour.
The problem here is that you are checking if it has returned rows or not, what you need instead is to check in each row if the field is empty
I suggest using underscore for iterating over each row:
_.each(result.rows,function(element, index){
if(element['brand_code'].length != 0){
codes.push(element['brand_code'])
}else{
console.log('empty field # results['+index+']')
}
})
CODE :
readCodes: function(callback) {
var pool = new pg.Pool(config.PG_CONFIG);
pool.connect(function(err, client, done) {
if(err){return console.error('Error acquiring client',err.stack);}
client.query(
'SELECT brand_code FROM public.voucher_codes',
function(err, result) {
if (err){console.log('[!] Error:',err); callback('');}
else if(result.rows.length == 0 ){
console.log('[!] Error:','No rows returned!');
callback('');
} else {
let codes = [];
_.each(result.rows,function(element, index){
console.log(element , index)
if(element['brand_code'].length != 0){
codes.push(element['brand_code'])
}else{
console.log('empty field # results['+index+']')
}
})
callback(codes);
}
});
});
}
I want to repeat the code until the user gets the no. right. How do I do this ?
This is the code:-
function getRandomNumber(min,max){
return Math.floor(Math.random()*(max - min + 1 ))+min;
}
randomNumber=(getRandomNumber(1,10));
input=prompt("Please enter a no. between 1 and 10:","");
if(input==randomNumber){
console.log("Good Work");
}else{
console.log("not matched");
}
You could either use a while loop that calls a "break" statement once the user inputs the correct answer, or you could use a function like this:
function getInput(){
input=prompt("Please enter a no. between 1 and 10:","");
if(input==randomNumber){
console.log("Good Work");
}else{
consol.log("not matched");
getInput(); //Gets the user's input again
}
}
Here you go...
Found needs to be set to false before you start, otherwise the function will only run one. There is little point having the function definition inside the while loop, since it will be created as a global variable.
var found = false;
function getRandomNumber(min,max) { return Math.floor(Math.random()*(max - min + 1 ))+min; }
while ( found != true ) {
var randomNumber = getRandomNumber(1,10);
console.log('Random Number is..',randomNumber);
var input = prompt("Please enter a no. between 1 and 10:","");
if ( input == randomNumber ) {
alert('Well Done')
found = true;
} else {
console.log("not matched");
}
}
What I want is when a user enters in a phone number into an input field, my cloud code will validate it. Below is what I have so far.
Parse.Cloud.beforeSave("Contact", function (request, response) {
var Contact = Parse.Object.extend("Contact");
var query = new Parse.Query(Contact);
query.equalTo("PhoneNo", request.object.get("PhoneNo"));
query.first({
success: function (object) {
var filterPhone = /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,3})|(\(?\d{2,3}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/;
if (!filterPhone.test(object.value)) {
response.error("Enter a valid phone number.");
return false;
} else {
response.success();
}
},
error: function (error) {
response.error("Could not validate phone number.");
}
});
});
I have used filterPhone below on the client side and that validates the phone number but I cant seem to get it to work on the cloud.
var phone = document.getElementById('Pno');
var filterPhone = /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,3})|(\(?\d{2,3}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/;
if (!filterPhone.test(phone.value)) {
alert('Please provide a valid phone number');
return false;
}
Thanks in advance.
Thomas.
I don't understand the need for a query. I believe you want something like this:
Parse.Cloud.beforeSave("Contact", function (request, response) {
var filterPhone = /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,3})|(\(?\d{2,3}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/;
if (!filterPhone.test(request.object.get("PhoneNo"))) {
response.error("Enter a valid phone number.");
} else {
response.success();
}
});
Am I missing something?
-Bob