`await` command causes variable to lose scope [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 4 years ago.
Improve this question
I am using await to pull data from the database. There's a variable secuity_ok that is true on one line, and then false on the next. Can anyone see what the issue is?
Note – if I comment out the line: let session = ..., then it all works.
Controller.prototype.changePassword = async function(request, response) {
let model = request.body;
var secuity_ok = false;
var user = await userService.getUserByEmail(model.email);
if (user && this.isAuthenticatedUser(request, user.id)) {
secuity_ok = true;
} else {
let session = await authenticationService.createSessionByEmailPassword(model.email, model.oldpassword),
secuity_ok = !!session;
console.log( 'A', secuity_ok ); // true
}
console.log( 'B', secuity_ok ); // false
if (!secuity_ok) {
this.sendForbiddenError(response, {
error: 'Cannot change password: Application safeguards are preventing this action'
});
return new Promise(() => {});
}
...
}
Output:
A true
B false
Output should be:
A true
B true

You have a comma at the end of the first line here:
let session = await authenticationService.createSessionByEmailPassword(model.email, model.oldpassword), // <--- Note comma here
secuity_ok = !!session;
That makes secuity_ok part of the let statement, so it's an extra, inner declaration of secuity_ok that only has scope inside the parentheses of the else clause.

Related

JavaScript unexpected undefined value [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 29 days ago.
Improve this question
I am running the following JavaScript code:
// Return true if the given username and password are in the database,
// false otherwise.
function validCredentials(enteredUsername, enteredPassword) {
// Database of usernames and passwords
let usernames = ["smith", "tron", "ace", "ladyj", "anon"];
let passwords = ["qwerty", "EndOfLine", "year1942", "ladyj123", "PASSWORD"];
// Search the usernames array for enteredUsername
// Only return true if the enteredUsername is in username, and the
// same location in passwords is enteredPassword
if (usernames.includes(enteredUsername)){
var correctPassword = passwords[usernames.indexOf(enteredUsername)];
if(enteredPassword == correctPassword){
return true;
}
}
else {
return false;
}
}
console.log("Login for ladyj: " + validCredentials("ladyj", "ladyj123")); // true
console.log("Login for ace: " + validCredentials("ace", "wrong")); // false
console.log("Login for jake: " + validCredentials("jake", "???")); // false
I am expecting console.log("Login for ace: " + validCredentials("ace", "wrong")); return false, but it returned undefined. Can anyone tell me what went wrong?
You don't return in all possible branches (namely, if the username exists, but the password is incorrect). Move the return false outside the else to be the final statement in the function.
Alternatively, you could simplify the chain of if and else into one statement:
return usernames.includes(enteredUsername) &&
passwords[usernames.indexOf(enteredUsername)] === enteredPassword;

TypeError: Cannot read properties of undefined (reading 'equal') [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 10 months ago.
Improve this question
I have created 2 TESTS --
In 2nd TEST, I have enclosed owner, addr1, addr2 in [] as per the Official Hardhat Documentation, like this const [owner,addr1,addr2] = await ethers.getSigners();,
But the problem is when I use [] bracket, it shows me the error TypeError: Cannot read properties of undefined (reading 'equal') and the test also failed,
Here is the Code --->
const { expect } = require('chai');
// const { ethers } = require('hardhat');
describe('Token contract', function () {
//1st TEST
it('Deployment should assign the total supply of the tokens to the owner', async function () {
const [owner] = await ethers.getSigners();
const Token = await ethers.getContractFactory('Token');
const hardhatToken = await Token.deploy();
const ownerBalance = await hardhatToken.balanceOf(owner.address);
expect(await hardhatToken.totalSupply()).to.equal(ownerBalance);
});
//2nd TEST
it('Should Transfer Tokens between accounts', async function () {
const [owner,addr1,addr2] = await ethers.getSigners();
const Token = await ethers.getContractFactory('Token');
const hardhatToken = await Token.deploy();
//Transfer 10 tokens from Owner to addr1
await hardhatToken.transfer(addr1.address,10);
expect(await hardhatToken.balanceOf(addr1.address).to.equal(10));
//Transfer 5 tokens from addr1 to addr2
await hardhatToken.connect(addr1).transfer(addr2.address,5);
expect(await hardhatToken.balanceOf(addr2.address).to.equal(5))
});
});
But if U see in the 1st TEST, I haven't used [], for owner, so the test passed.
Below is the Official Hardhat documentation if U want to check the code --->
https://hardhat.org/tutorial/testing-contracts.html
Please help me to solve this Problem
Thanks
enter image description here
You didn't close the parenthesis around the expect calls in the second test correctly. You're accessing .to on the number returned by .balanceOf.
Replace with:
expect(await hardhatToken.balanceOf(addr1.address)).to.equal(10);
// ...
expect(await hardhatToken.balanceOf(addr2.address)).to.equal(5);

Second Line of Else Block Not Running [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 12 months ago.
Improve this question
In my else block, the second line does not appear to be running. It runs setHelperText but seems to ignore setAlertValue.
const [alertValue, setAlertValue] = useState("error");
const [errValue, setErrorValue] = useState("Error State");
const [helperText, setHelperText] = useState('Input "success" to remove error');
const handleChange = (e) => {
setErrorValue(e.target.value);
if (e.target.value === "success") {
setAlertValue(null);
setHelperText("Update input to re-enable error");
} else
setHelperText('Input "success" to remove error');
setAlertValue("error"); // this line does not run
};
<TextField
label="Error State"
message="this is an ERROR message"
alert={alertValue}
value={errValue}
onChange={handleChange}
helperText={helperText}
/>
Curly braces are missing in your code. It should be like this:
if (e.target.value === "success") {
setAlertValue(null);
setHelperText("Update input to re-enable error");
} else {
setHelperText('Input "success" to remove error');
setAlertValue("error");
};

function breaks if id doesn't come [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 1 year ago.
Improve this question
Error : Cannot read property id of undefined
How can I re-write this function so that it doesn't break foundApplication[0].id, if id doesn't come or foundApplication array comes empty?
I cannot alter getDocument function
async function getApplicationByCbaxUid(cbaxUid) {
let foundApplication = await dbService.application
.find({ userID: cbaxUid });
return getDocument(foundApplication[0].id);
}
You can validate if the array and the id exist. if you're using latest version of ES, you can use optional chaining (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining):
async function getApplicationByCbaxUid(cbaxUid) {
let foundApplication = await dbService.application
.find({ userID: cbaxUid });
return getDocument(foundApplication?.[0]?.id);
}
if you don't
async function getApplicationByCbaxUid(cbaxUid) {
let foundApplication = await dbService.application
.find({ userID: cbaxUid });
return foundApplication.length && foundApplication[0].id && getDocument(foundApplication[0].id);
}
This is doing all the normal validations which the latest operator (optional chaining is doing)
You can just add a check if the array is empty
return foundApplication.length ? getDocument(foundApplication[0].id) : null;
set an if statement and add whatever you need to do if it fails to the else block
async function getApplicationByCbaxUid(cbaxUid) {
let foundApplication = await dbService.application
.find({ userID: cbaxUid });
if(foundApplication.length){
return getDocument(foundApplication[0].id)
}else{
...do what you want here
}
}

Why are my variables not being correctly defined in my if...else statement? [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
In the code below, I've defined a function called checkPassword(), which takes in a single argument, passwordCorrect, which will be either true or false.
I've also defined two variables, accessGranted and message, which currently have no values (they're undefined) and will be overwritten and defined by your if statement if you've written it correctly.
I need to write an if statement inside the function that updates the two variables, accessGranted (a boolean), and message (a string), to meet the requirements below
Requirements:
1) If passwordCorrect is true, accessGranted should have a value of true and message should have a value of 'Welcome to the admin panel!'
2) In any other case, accessGranted should have a value of false and message should have a value of 'Wrong password.'
var accessGranted;
var message;
function checkPassword(passwordCorrect) {
if passwordCorrect == true {
accessGranted = true;
message = "Welcome to the admin panel!";
}
else {
accessGranted = false;
message = "Wrong password."
}
}
console.log('Access Granted:', accessGranted);
console.log('Message:', message);
You need to call the function and fix your syntax error. If statements need parentheses in javascript.
let accessGranted;
let message;
function checkPassword(passwordCorrect) {
if (passwordCorrect) {
accessGranted = true;
message = "Welcome to the admin panel!";
}
else {
accessGranted = false;
message = "Wrong password."
}
}
checkPassword(true)
console.log('Access Granted:', accessGranted);
console.log('Message:', message);

Categories