In this JavaScript code they had 17 test cases, all the 17 test cases two test cases are not comming they are
When the reset button is clicked, an HTTP request should be made to get a random quotation from the given URL and the value in the HTML paragraph element with id quoteDisplay should be replaced with quotation received in the response
When page is opened, an HTTP request should be made to get a random quotation from the given URL and the HTML paragraph element with id quoteDisplay should have the quotation received in the response.
Please help me
let timerEl = document.getElementById("timer");
let speedTypingTestEl = document.getElementById("speedTypingTest");
let quoteDisplayEl = document.getElementById("quoteDisplay");
let quoteInputEl = document.getElementById("quoteInput");
let submitBtnEl = document.getElementById("submitBtn");
let resetBtnEl = document.getElementById("resetBtn");
let spinnerEl = document.getElementById("spinner");
let countdown = 0;
function getQuoteDisplay() {
let randomUrl = "https://apis.ccbp.in/random-quote";
let options = {
method: "GET",
};
fetch(randomUrl, options)
.then(function(response) {
return response.json();
})
.then(function(jsonData) {
quoteDisplay(jsonData.content); // use jsonData.content instead
});
}
submitBtn.addEventListener("click", function() {
let intervalId = setInterval(function() {
countdown = countdown + 1;
timerEl.textContent = countdown;
}, 1000);
});
spinnerEl.classList.add("d-none");
for (let result of searchResults) {
createAndAppendSearchResult(result);
}
function searchWikipedia(event) {
if (event.key === "Enter") {
spinnerEl.classList.remove("d-none");
searchResultsEl.textContent = "";
let searchInput = quoteInputEl.value;
let url = "https://apis.ccbp.in/random-quote" + quoteInput;
let options = {
method: "GET"
};
fetch(url, options)
.then(function(response) {
return response.json();
})
.then(function(jsonData) {
let {
search_results
} = jsonData;
displayResults(search_results);
});
}
}
resetBtnEl.addEventListener("click", function() {
getAllValues();
var string_a = jsonData.content;
var string_b = str;
var n = string_a.localeCompare(string_b);
var textVal = document.getElementById('quoteInput').value;
if (n == 1 && textVal == "") {
clearInterval(cancel);
feedback.innerText = "You typed in " + seconds + " seconds";
} else if (n == -1 || textVal == "") {
feedback.innerText = "You typed incorrect sentence";
} else {}
});
Related
I am making a list where you can edit or delete items. I am listening for 2 events on the same table. One for edit and one for delete, I am listening on the table and not the actual buttons as they are created dinamycally. Edit and Delete both have the same id, the id of the product, which I am using later for the http requests.
,
Now when I press edit the console.logs from the delete functions fire up,but nothing happens, if I am trying to save the item the http request doesnt work, it will not take the id (but it logs it to the console)
If I press the delete button once nothing happnes, if I press it a second time the page refreshes and the item is deleted.
Is there a way to listen for those events separately or for them to not interfere with one another? All I want is if I press the edit button the respective item's values to go to the input field and when I press Add Item update the product in the JSON file as well, and on delete press, to delete the item from the JSON file and remove from the html document.
Update: Managed to resolve edit function
Here is my code:
import { http } from "./http.js";
import { ui } from "./ui.js";
const productsURL = "https://61363d1a8700c50017ef54c1.mockapi.io/product";
// const addProductBtn = document.querySelector('.new-product-btn');
const adminContainer = document.querySelector('.admin-container');
const addItem = document.querySelector('.admin-add-item-btn');
const imgInput = document.getElementById('image');
const nameInput = document.getElementById('name');
const priceInput = document.getElementById('price');
const stockInput = document.getElementById('stock');
const categoryInput = document.getElementById('category');
const typeInput = document.getElementById('type');
const descriptionInput = document.getElementById('description');
const validSvg = document.querySelectorAll('.valid_input_svg');
// const adminForm = document.getElementById('admin-form');
const adminTable = document.getElementById('admin-tbody');
const editBtn = document.querySelectorAll('.edit-btn');
const adminBtn = document.querySelectorAll('.admin-delete-btn');
const cancel = document.getElementById('cancel');
let productToEdit;
let edit = false;
let id;
document.addEventListener('DOMContentLoaded', listAdminProducts);
// adminForm.addEventListener('submit', validateInput);
addItem.addEventListener('click', addOrEditProducts);
// adminTable.addEventListener('click', editOrDeleteItem);
adminTable.addEventListener('click', deleteProduct);
adminTable.addEventListener('click', editProduct);
cancel.addEventListener('click', cancelEdit);
function listAdminProducts() {
http.get(productsURL).then(products => {
ui.showAllAdminProducts(products);
});
};
function addOrEditProducts() {
if (edit === true && validateInput() === true) {
productToEdit = {
image: imgInput.value,
name: nameInput.value,
price: priceInput.value,
stock: stockInput.value,
category: categoryInput.value,
type: typeInput.value,
description: descriptionInput.value,
};
http
.put(`${productsURL}/${id}`, productToEdit)
.then(() => listAdminProducts());
console.log(`${productsURL}/${id}`)
ui.clearFields();
id = '';
edit = false;
return;
} else if (edit === false && validateInput() === true) {
const product = {
image: imgInput.value,
name: nameInput.value,
price: priceInput.value,
stock: stockInput.value,
category: categoryInput.value,
type: typeInput.value,
description: descriptionInput.value
};
http.post(productsURL, product).then(() => listAdminProducts());
ui.clearFields();
};
};
function editProduct(e) {
console.log('works');
if (e.target.classList.contains('edit-btn')) {
edit = true;
id = e.target.getAttribute('id');
console.log(id);
console.log(e.target)
http.get(`${productsURL}/${id}`).then((data) => {
imgInput.value = data.image;
nameInput.value = data.name;
priceInput.value = data.price;
stockInput.value = data.stock;
categoryInput.value = data.category;
typeInput.value = data.type;
descriptionInput.value = data.description;
});
console.log(`${productsURL}/${id}`)
};
// id = '';
}
function deleteProduct(e) {
console.log(e.target);
if (e.target.className === 'admin-delete-btn') {
console.log(e.target);
id = e.target.getAttribute('id');
console.log(id);
http
.delete(`${productsURL}/${id}`)
.then(() => listAdminProducts())
.catch("Error on delete");
id = '';
}
ui.showSuccessMessage('Product deleted', adminContainer);
}
function cancelEdit() {
ui.clearFields;
imgInput.className = '';
nameInput.className = '';
priceInput.className = '';
stockInput.className = '';
categoryInput.className = '';
edit = false;
}
function validateInput() {
let valid = true;
if (imgInput.value == '') {
if (imgInput.classList.contains('input-invalid')) {
imgInput.classList.remove('input-invalid');
};
ui.showAdminMessage('Must contain a link to an image', 0);
imgInput.classList.add('input-invalid');
valid = false;
} else {
imgInput.classList.add('input-valid');
validSvg[0].style.display = "block";
removeClass(imgInput, 0);
};
if (nameInput.value === '') {
if (nameInput.classList.contains('input-invalid')) {
nameInput.classList.remove('input-invalid');
};
ui.showAdminMessage('Name is requierd', 1);
nameInput.classList.add('input-invalid');
valid = false;
} else {
// stockInput.classList.remove('input-invalid');
nameInput.classList.add('input-valid');
validSvg[1].style.display = "block";
removeClass(nameInput, 1);
};
if (priceInput.value == "" || isNaN(priceInput.value) || priceInput.value < 0) {
if (priceInput.classList.contains('input-invalid')) {
priceInput.classList.remove('input-invalid');
};
ui.showAdminMessage('Price must be a number greater then 0', 2);
priceInput.classList.add('input-invalid');
valid = false;
} else {
// stockInput.classList.remove('input-invalid');
priceInput.classList.add('input-valid');
validSvg[2].style.display = "block";
removeClass(priceInput, 2);
};
if (stockInput.value == "" || isNaN(stockInput.value) || stockInput.value < 0) {
if (stockInput.classList.contains('input-invalid')) {
stockInput.classList.remove('input-invalid');
};
ui.showAdminMessage('Stock must be a number greater then 0', 3);
stockInput.classList.add('input-invalid');
valid = false;
} else {
// stockInput.classList.remove('input-invalid');
stockInput.classList.add('input-valid');
validSvg[3].style.display = "block";
removeClass(stockInput, 3);
};
if (categoryInput.value === 'barware' || categoryInput.value === 'spirits') {
// categoryInput.classList.remove('input-invalid');
categoryInput.classList.add('input-valid');
validSvg[4].style.display = "block";
removeClass(categoryInput, 4);
} else {
ui.showAdminMessage('Category must be barware or spirits', 4);
categoryInput.classList.add('input-invalid');
valid = false;
};
return valid;
};
function removeClass(element, index) {
// console.log(element, index);
setTimeout(() => {
element.className = '';
validSvg[index].style.display = "none";
}, 3000)
}
Finally managed to resolve it, I had to put e.preventDefault() in both functions, so the page will not reload first
Why are my variables being alerted back to me as null?
So, I'm trying to pass a string in a variable back to a main page from an external javascript page via alerts.
At first I thought that the javascript wasn't pulling information from the php page properly, then I tried just typing in a variable directly on the javascript page. Both the pulled information and the information that I described on the javascript directly send null.
Now I know for a fact that the varibles name and email are not null, as I literally just defined them.
Here is the code I am having an issue with.
let name = "test";
let email = 11;
let company = document.getElementById($("#Company").value);
let phone = document.getElementById($("#Phone").value);
let city = document.getElementById($("#City").value);
let state = document.getElementById($("#State").value);
let country = document.getElementById($("#Country").value);
alert("Test Alert");
alert(name);
alert(email);
alert(company);
alert(phone);
alert(city);
alert(state);
alert(country);
Here is the full javascript file:
ROICalc3.js
const getErrorMsg2 = lbl =>
`${lbl} must be a valid percent less than or equal to 100.`;
const focusAndSelect = selector => {
const elem = $(selector);
elem.focus();
elem.select();
};
const processEntries = () => {
let ActiveNumberOfMolds = parseFloat($("#activeNumberOfMolds").value);
let PercentOfDownMolds = parseFloat($("#percentOfDownMolds").value);
PercentOfDownMolds = PercentOfDownMolds * .01;
let AverageLaborHours = parseFloat($("#averageLaborHours").value);
let RepairRatePerHour = parseFloat($("#repairRatePerHour").value);
let CostOfCurrentLifter = parseFloat($("#costOfCurrentLifter").value);
let AverageProfitPerPressHour = parseFloat($("#averageProfitPerPressHour").value);
let EstimatedPriceOfAnAcculifter = parseFloat($("#estimatedPriceOfAnAcculifter").value);
let PercentageReductionInLifterFailureUsingAcculignLifters = parseFloat($("#percentageReductionInLifterFailureUsingAcculignLifters").value);
let AverageNumberOfLiftersPerMold = parseFloat($("#averageNumberOfLiftersPerMold").value);
PercentageReductionInLifterFailureUsingAcculignLifters = PercentageReductionInLifterFailureUsingAcculignLifters * .01;
let LifterCostDifference = (EstimatedPriceOfAnAcculifter - CostOfCurrentLifter);
if (isNaN(ActiveNumberOfMolds) || ActiveNumberOfMolds <= 0) {
alert(getErrorMsg("Enter The Active Number Of Molds"));
focusAndSelect("#activeNumberOfMolds");
} else if (isNaN(AverageNumberOfLiftersPerMold) || AverageNumberOfLiftersPerMold <= 0) {
alert(getErrorMsg("Enter the Average Number Of Lifters Per Mold:"));
focusAndSelect("#averageNumberOfLiftersPerMold");
} else if (isNaN(PercentOfDownMolds) || PercentOfDownMolds <= 0) {
alert(getErrorMsg("Enter the Percentage Of Down Molds:"));
focusAndSelect("#percentOfDownMolds");
} else if (isNaN(AverageLaborHours) || AverageLaborHours <= 0) {
alert(getErrorMsg("Enter the Average Labor Hours:"));
focusAndSelect("#averageLaborHours");
} else if (isNaN(RepairRatePerHour) || RepairRatePerHour <= 0) {
alert(getErrorMsg("Enter the repair rate per hour:"));
focusAndSelect("#repairRatePerHour");
} else if (isNaN(AverageProfitPerPressHour) || AverageProfitPerPressHour <= 0) {
alert(getErrorMsg("Enter the average profit per press hour:"));
focusAndSelect("#averageProfitPerPressHour");
} else if (isNaN(CostOfCurrentLifter) || CostOfCurrentLifter <= 0) {
alert(getErrorMsg("Enter the average profit per press hour:"));
focusAndSelect("#costOfCurrentLifter");
} else if (isNaN(EstimatedPriceOfAnAcculifter) || EstimatedPriceOfAnAcculifter <= 0) {
alert(getErrorMsg("Enter the estimated price of an acculifter:"));
focusAndSelect("#estimatedPriceOfAnAcculifter");
} else if (PercentageReductionInLifterFailureUsingAcculignLifters <= 0) {
alert(getErrorMsg("Enter the percentage reduction in lifter failure using accualign lifters:"));
focusAndSelect("#percentageReductionInLifterFailureUsingAcculignLifters");
} else if (PercentOfDownMolds > 1) {
alert(getErrorMsg2("Enter the percentage of down molds:"));
focusAndSelect("#percentOfDownMolds");
} else if (PercentageReductionInLifterFailureUsingAcculignLifters > 1) {
alert(getErrorMsg2("Enter the Percentage Reduction In Lifter Failure Using Accualign Lifters:"));
focusAndSelect("#percentageReductionInLifterFailureUsingAccualignLifters");
} else {
$("#MRRPA").value = (ActiveNumberOfMolds * PercentOfDownMolds);
let mrrpa = parseFloat($("#MRRPA").value);
$("#ANHPL").value = (mrrpa * AverageLaborHours);
let anhpl = parseFloat($("#ANHPL").value);
$("#ALCRFLPM").value = ((anhpl * RepairRatePerHour) + (mrrpa * CostOfCurrentLifter * AverageNumberOfLiftersPerMold));
let alcrflpm = parseFloat($("#ALCRFLPM").value);
$("#PLDDM").value = (AverageProfitPerPressHour * anhpl * .3);
let plddm = parseFloat($("#PLDDM").value);
let eacfl = (plddm + alcrflpm);
$("#EACFL").value = (eacfl);
$("#CDBCLVAL").value = (EstimatedPriceOfAnAcculifter - CostOfCurrentLifter);
let pldtd = (PercentageReductionInLifterFailureUsingAcculignLifters * plddm);
let cdbclval = parseFloat($("#CDBCLVAL").value);
$("#TCDBCLVAL").value = (cdbclval * (ActiveNumberOfMolds * AverageNumberOfLiftersPerMold));
let tcdbclval = parseFloat($("#TCDBCLVAL").value);
let acrnm = ((anhpl * RepairRatePerHour * PercentageReductionInLifterFailureUsingAcculignLifters) + (EstimatedPriceOfAnAcculifter * AverageNumberOfLiftersPerMold * ActiveNumberOfMolds * PercentOfDownMolds * PercentageReductionInLifterFailureUsingAcculignLifters));
let cdnlptrc = (tcdbclval + acrnm + pldtd);
let rlfcical = (eacfl - cdnlptrc);
$("#RLFCICAL").value = rlfcical;
$("#EMUUPI").value = ((tcdbclval / rlfcical) * 12).toFixed(2);;
let emuupi = parseFloat($("#EMUUPI").value);
console.log("EACFL: " + eacfl);
console.log("cdnlptrc: " + cdnlptrc);
document.getElementById("MRRPA").innerHTML = mrrpa + " Molds";
document.getElementById("ANHPL").innerHTML = anhpl + " Hours";
document.getElementById("ALCRFLPM").innerHTML = "$" + alcrflpm;
document.getElementById("PLDDM").innerHTML = "$" + plddm;
document.getElementById("CDBCLVAL").innerHTML = "$" + cdbclval;
document.getElementById("TCDBCLVAL").innerHTML = "$" + tcdbclval;
document.getElementById("RLFCICAL").innerHTML = "$" + rlfcical;
document.getElementById("EACFL").innerHTML = "$" + eacfl;
document.getElementById("EMUUPI").innerHTML = emuupi + " Months";
document.getElementById("ACRNM").innerHTML = "$" + acrnm;
document.getElementById("PLDTD").innerHTML = "$" + pldtd;
document.getElementById("CDNLPTRC").innerHTML = "$" + cdnlptrc;
if (rlfcical > 0) {
document.getElementById("RLFCICAL").style.color = "green";
} else {
document.getElementById("RLFCICAL").style.color = "red";
}
if (eacfl > 0) {
document.getElementById("EACFL").style.color = "red";
} else {
document.getElementById("EACFL").style.color = "green";
}
if (alcrflpm > 0) {
document.getElementById("ALCRFLPM").style.color = "red";
} else {
document.getElementById("ALCRFLPM").style.color = "green";
}
if (plddm > 0) {
document.getElementById("PLDDM").style.color = "red";
} else {
document.getElementById("PLDDM").style.color = "green";
}
if (tcdbclval > 0) {
document.getElementById("TCDBCLVAL").style.color = "red";
} else {
document.getElementById("TCDBCLVAL").style.color = "green";
}
if (cdbclval) {
document.getElementById("CDBCLVAL").style.color = "red";
} else {
document.getElementById("CDBCLVAL").style.color = "green";
}
if (emuupi > 0) {
document.getElementById("EMUUPI").style.color = "green";
} else {
document.getElementById("EMUUPI").style.color = "red";
}
if (anhpl > 0) {
document.getElementById("ANHPL").style.color = "red";
} else {
document.getElementById("ANHPL").style.color = "green";
}
if (mrrpa > 0) {
document.getElementById("MRRPA").style.color = "red";
} else {
document.getElementById("MRRPA").style.color = "green";
}
if (acrnm > 0) {
document.getElementById("ACRNM").style.color = "red";
} else {
document.getElementById("ACRNM").style.color = "green";
}
if (pldtd > 0) {
document.getElementById("PLDTD").style.color = "red";
} else {
document.getElementById("PLDTD").style.color = "green";
}
if (cdnlptrc > 0) {
document.getElementById("CDNLPTRC").style.color = "red";
} else {
document.getElementById("CDNLPTRC").style.color = "green";
}
let name = "test";
let email = 11;
let company = document.getElementById($("#Company").value);
let phone = document.getElementById($("#Phone").value);
let city = document.getElementById($("#City").value);
let state = document.getElementById($("#State").value);
let country = document.getElementById($("#Country").value);
alert("Test Alert");
alert(name);
alert(email);
alert(company);
alert(phone);
alert(city);
alert(state);
alert(country);
let result = document.querySelector('.result');
// Creating a XHR object
let xhr = new XMLHttpRequest();
let url = "https://staging-dmecompany.kinsta.cloud/Submissions/submitjson.php";
// open a connection
xhr.open("POST", url, true);
// Set the request header i.e. which type of content you are sending
xhr.setRequestHeader("Content-Type", "application/json");
// Create a state change callback
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
// Print received data from server
document.getElementById("result").innerHTML = this.responseText;
}
};
// Converting JSON data to string
var data = JSON.stringify({
"Name": name,
"Email": email,
"Company": company,
"Phone": phone,
"City": city,
"State": state,
"Country": country,
"ActiveNumberOfMolds": ActiveNumberOfMolds,
"PercentOfDownMolds": PercentOfDownMolds,
"Average Labor Hours": AverageLaborHours,
"RepairRatePerHour": RepairRatePerHour,
"AverageProfitPerPressHour": AverageProfitPerPressHour,
"AverageNumberOfLiftersPerMold": AverageNumberOfLiftersPerMold,
"rlfcical": rlfcical,
"LifterCostDifference": LifterCostDifference,
"anhpl": anhpl,
"alcrflpm": alcrflpm,
"plddm": plddm,
"cdbclval": cdbclval,
"pldtd": pldtd,
"cdbclval": cdbclval,
"emuupi": emuupi,
"mrrpa": mrrpa,
"acrnm": acrnm,
"pldtd": pldtd,
"cdnlptrc": cdnlptrc
});
// Sending data with the request
xhr.send(data);
}
};
document.addEventListener("DOMContentLoaded", () => {
$("#calculate").addEventListener("click", processEntries);
$("#activeNumberOfMolds").focus();
});
Can you tell me why these variables are getting alerted back to me as null?
Edit: #1:
I tried swapping the code to this:
let name = "test";
let email = 11;
let company = document.getElementById("Company").value;
let phone = document.getElementById("Phone").value;
let city = document.getElementById("City").value;
let state = document.getElementById("State").value;
let country = document.getElementById("Country").value;
alert("Test Alert");
alert(name);
alert(email);
alert(company);
alert(phone);
alert(city);
alert(state);
alert(country);
The first alert had, "test"
The second alert had, "11"
All of the rest of the alerts were, "Undefined".
The alerts seem to be feeding back data now if the variables are described in the javascript code itself. I don't seem to be able to pull them from my php file.
.value should not be in the argument to document.getElementById(), it should be used on the result of this.
And you shouldn't call $() or use the # prefix in the argument to getElementById(), the argument should just be the ID by itself.
let company = document.getElementById($("#Company").value);
should be
let company = document.getElementById("Company").value;
Or if $() is an abbreviation for document.querySelector(), you can write
let company = $("#Company").value;
If it's jQuery, then the correct syntax is
let company = $("#Company").val();
I have a callback function inside a loop here for (var res in results) {
but it seems the loop is not waiting for the async call. When I am calling self.callTestOutputData(test_output_url) here, the loop is not waiting fpor the response but continuing for the next iteration and I am losing out the value to push into obj.requistion_number = testOutputResponse.value;
Please note : var results = response.results Here results is an array of Json objects.
Edit 1 : I tried forEach but that didn't work .
results.forEach(res => {
var obj = {}
obj.ferp = res.name;
// your code...
})
Original Code:
self.downloadDailyExcelProcurement = function (filters, excelTmpArr) {
self.disableExcelDownloadProcurement(true);
$('.useCaseExcelButtonProcurement .oj-button-button .oj-button-label')[0].style.backgroundColor = "gray";
$('.useCaseExcelButtonProcurement .oj-button-button .oj-button-label .demo-download-icon-24')[0].style.color = "#D8D8D8";
var payload = {};
if (typeof filters === "string") {
var fill = filters;
} else {
var fill = self.sendFilters();
if(self.app() === "fusion"){
fill += '&module=Procurement';
}else if (self.app() === "o2r"){
fill += '&module=O2r';
}
}
if(fill.includes("%3A")){
fill = fill.replace(/%3A/g, ':');
}
payload.Endpoint = 'executions/testcollection/' + fill;
//console.log(payload.Endpoint)
payload.BeforeSend = function (xhr) {
xhr.setRequestHeader('Authorization', 'Basic ' + btoa('guest:oracle123'));
$(".custom-loader-circle").show();
};
payload.OnSuccess = function (response) {
var results = response.results;
for (var res in results) {
var obj = {}
obj.ferp = results[res].name;
obj.po = "NA"
obj.receipt_no = "NA"
var test_output_url = results[res].reference_test_cases[0].automation_tests[0].test_outputs[0]
$.when(self.callTestOutputData(test_output_url)).done(function (testOutputResponse) {
if(testOutputResponse)
obj.requistion_number = testOutputResponse.value;
else {
obj.requistion_number = "NA";
}
self.excelTmpArr().push(obj);
});
}
else {
self.excelTmpArr().push(obj);
}
}
if (response.next) {
filters = ((response.next).split('testcollection'))[1];
if (filters[0] === "/") {
var test = filters.slice(1, filters.length);
}
self.downloadDailyExcelProcurement(test, self.excelTmpArr());
} else {
if (results.length === 0) {
$(".custom-loader-circle").hide();
self.disableExcelDownloadProcurement(false);
$('.useCaseExcelButtonProcurement .oj-button-button .oj-button-label')[0].style.backgroundColor = "#4d0000";
$('.useCaseExcelButtonProcurement .oj-button-button .oj-button-label .demo-download-icon-24')[0].style.color = "white";
showMessage(self.messages, "No Data to Download", '', 'info');
} else {
self.formatForExcel(self.excelTmpArr(), fill, "Procurement");
}
}
};
payload.OnError = function (data) {
showMessage(self.messages, data.status, data.statusText, 'error');
$(".custom-loader-circle").hide();
};
getData(payload);
}
Try using async and await :
async function asyncCall () {
// call here
}
for (var res in results) {
const response = await asyncCall();
}
var results = response.results;
if(result.length > 0){
results.map((data,index)=>{
//write your code here
})
}
This will help you ..
Use forEach() to iterate since it creates its own function closure:
results.forEach(res => {
var obj = {}
obj.ferp = res.name;
// your code...
})
I have a problem when using await in a for loop. Every time it hits the await funtion it executes it fine, but it stops loping through the rest of the array that is looping through. I'm using nodejs with axios to send http request to a restAPI. The function that is in the api is big. So I thought maby that is the problem but it wasn't. Also the api uses its own await functions to, but that wasn't the problem either(As far as I know).
Here is my code for the request
var files = await globPromise("assets/series/**/*.json");
var json = null;
var file = null;
var series = [];
for (i = 0; i < files.length; i++) {
file = files[i];
var raw = fs.readFileSync(file);
json = JSON.parse(raw);
if (json.type === "series") {
try {
var userId = null;
if (req.user == null) {
userId = req.query.userid;
} else {
userId = req.user.id;
}
const response = await axios.get("http://" + host + "/series/info/" + json.id + "?userid=" + userId);
series.push(JSON.parse(response.data));
} catch (error) {
console.log(error);
series.push(json);
}
}
}
res.json(JSON.stringify(series));
});
And also the api side:
app.get('/series/info/:id', async(req, res) => {
var files = await globPromise("assets/series/**/*.json");
var json = null;
var file = null;
for (i = 0; i < files.length; i++) {
file = files[i];
var raw = fs.readFileSync(file);
json = JSON.parse(raw);
if (json.type === "series" && json.id === req.params.id) {
break;
}
json = null;
}
let path = pathFs.dirname(file) + "/";
try {
var seriesFiles = await fsPromise.readdir(path);
var latestWatchedVideo = null;
var latestWatchedTime = null;
var latestWatchTime = null;
var latestWatchDuration = null;
var seasonCount = 0;
var seasons = [];
for (i = 0; i < seriesFiles.length; i++) {
seriesFile = seriesFiles[i];
if (fs.lstatSync(path + "/" + seriesFile).isDirectory()) {
if (!seriesFile.startsWith("s")) {
continue;
}
seasonCount++;
try {
var videoFiles = await fsPromise.readdir(path + "/" + seriesFile + "/");
var videos = [];
for (let i = 0; i < videoFiles.length; i++) {
const video = videoFiles[i];
if (video.endsWith(".json")) {
var rawVideo = fs.readFileSync(path + "/" + seriesFile + "/" + video);
videoJson = JSON.parse(rawVideo);
const query = util.promisify(con.query).bind(con);
var userId = null;
if (req.user == null) {
userId = req.query.userid;
} else {
userId = req.user.id;
}
var results = await query(`SELECT * FROM watched WHERE video_id = "${videoJson.id}" AND user_id = "${userId}"`);
if (results.length > 0) {
var updated = JSON.parse(JSON.stringify(results[0].updated));
var duration = JSON.parse(JSON.stringify(results[0].duration));
var time = JSON.parse(JSON.stringify(results[0].time));
if (latestWatchedVideo == null) {
latestWatchedVideo = videoJson.id;
latestWatchedTime = updated;
latestWatchTime = time;
latestWatchDuration = duration;
} else {
if (latestWatchedTime < updated) {
latestWatchedVideo = videoJson.id;
latestWatchedTime = updated;
latestWatchTime = time;
latestWatchDuration = duration;
}
}
}
videos.push(videoJson);
}
}
function compare(a, b) {
if (a.episode < b.episode) {
return -1;
}
if (a.episode > b.episode) {
return 1;
}
return 0;
}
videos.sort(compare);
seasons.push({
season: seasonCount,
title: seriesFile.replace("s" + seasonCount, ""),
videos: videos
});
} catch (error) {
console.log(error);
}
}
}
json.seasonCount = seasonCount;
json.seasons = seasons;
json.latestWatchDuration = latestWatchDuration;
json.latestWatchTime = latestWatchTime;
json.latestWatchedVideo = latestWatchedVideo;
json.latestWatchedTime = latestWatchedTime;
res.json(JSON.stringify(json));
} catch (error) {
console.log(error);
}
});
Is there something (important) about await and async that I've missed?
Edit: my problem is that is loops fine through the first item and the await is working fine too, but it stops the loop and executes the next lines of code like there are no other items in my array.
Solved: I tried using the for/of and it works now. I don't know whats is so different between de default for and this one but it works!
I am trying to fix this script to automatically connect people you may know on Linkedin based on User roles (CEO e.t.c), Can someone help me fix this, Below is my code; I have tried the script on almost all browsers, Somebody help fix this.
var userRole = [
"CEO",
"CIO"
];
var inviter = {} || inviter;
inviter.userList = [];
inviter.className = 'button-secondary-small';
inviter.refresh = function () {
window.scrollTo(0, document.body.scrollHeight);
window.scrollTo(document.body.scrollHeight, 0);
window.scrollTo(0, document.body.scrollHeight);
};
inviter.initiate = function()
{
inviter.refresh();
var connectBtns = $(".button-secondary-small:visible");
//
if (connectBtns == null) {var connectBtns = inviter.initiate();}
return connectBtns;
};
inviter.invite = function () {
var connectBtns = inviter.initiate();
var buttonLength = connectBtns.length;
for (var i = 0; i < buttonLength; i++) {
if (connectBtns != null && connectBtns[i] != null) {inviter.handleRepeat(connectBtns[i]);}
//if there is a connect button and there is at least one that has not been pushed, repeat
if (i == buttonLength - 1) {
console.log("done: " + i);
inviter.refresh();
}
}
};
inviter.handleRepeat = function(button)
{
var nameValue = button.children[1].textContent
var name = nameValue.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
function hasRole(role){
for(var i = 0; i < role.length; i++) {
// cannot read children of undefined
var position = button.parentNode.parentNode.children[1].children[1].children[0].children[3].textContent;
var formatedPosition = position.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
var hasRole = formatedPosition.indexOf(role[i]) == -1 ? false : true;
console.log('Has role: ' + role[i] + ' -> ' + hasRole);
if (hasRole) {
return hasRole;
}
}
return false;
}
if(inviter.arrayContains(name))
{
console.log("canceled");
var cancel = button.parentNode.parentNode.children[0];
cancel.click();
}
else if (hasRole(userRole) == false) {
console.log("cancel");
var cancel = button.parentNode.parentNode.children[0];
cancel.click();
}
else if (button.textContent.indexOf("Connect")<0){
console.log("skipped");
inviter.userList.push(name); // it's likely that this person didn't join linkedin in the meantime, so we'll ignore them
var cancel = button.parentNode.parentNode.children[0];
cancel.click();
}
else {
console.log("added");
inviter.userList.push(name);
button.click();
}
};
inviter.arrayContains = function(item)
{
return (inviter.userList.indexOf(item) > -1);
};
inviter.usersJson = {};
inviter.loadResult = function()
{
var retrievedObject = localStorage.getItem('inviterList');
var temp = JSON.stringify(retrievedObject);
inviter.userList = JSON.parse(temp);
};
inviter.saveResult = function()
{
inviter.usersJson = JSON.stringify(inviter.userList);
localStorage.setItem('inviterList', inviter.usersJson);
};
setInterval(function () { inviter.invite(); }, 5000);
`
When I try executing this, I get the following error:
VM288:49 Uncaught TypeError: Cannot read property 'children' of undefined
at hasRole (<anonymous>:49:71)
at Object.inviter.handleRepeat (<anonymous>:66:11)
at Object.inviter.invite (<anonymous>:30:69)
at <anonymous>:108:35
Any ideas as to how to fix it?