Intended of Load JQuery once function in other js file executed completely - javascript

I am fetching some data from the database and based on retrieved data HTML is being rendered on the browser. Once the HTML is being rendered then I want to apply JQuery on them. following is my code
fetch_items.js File
async function itemsWithAllDetails() {
let responseData = await retrieveItems();
let itemsWithSizes = await getSizes(responseData);
let itemsWithImages = await getImages(itemsWithSizes);
let itemsWithColors = await getColors(itemsWithImages);
let filtered_items_sales = filterItems(itemsWithColors, 'sales_section');
renderItems(filtered_items_sales, "sales_section");
let filtered_items_boys = filterItems(itemsWithColors, 'BOYS');
renderItems(filtered_items_boys, "boys_section");
let filtered_items_girls = filterItems(itemsWithColors, 'GIRLS');
renderItems(filtered_items_girls, "girls_section");
let filtered_items_bboys = filterItems(itemsWithColors, 'BABY BOYS');
renderItems(filtered_items_bboys, "baby_boy_section");
let filtered_items_bgirls = filterItems(itemsWithColors, 'BABY GIRLS');
renderItems(filtered_items_bgirls, "baby_girl_section");
let filtered_items_men = filterItems(itemsWithColors, 'MEN');
renderItems(filtered_items_men, "men_section");
let filtered_items_women = filterItems(itemsWithColors, 'WOMEN');
renderItems(filtered_items_women, "women_section");
}
itemsWithAllDetails();
JQuery File
$(document).ready(function () {
$("button.increament").click(function () {
let x = $(this).siblings("input").val();
if (x == "") {
x = 0;
}
x = parseInt(x);
if (x >= 5) {
alert("You can not order more than 5");
}
else {
$(this).siblings("input").val(x + 1);
}
});
$("button.decreament").click(function () {
let x = $(this).siblings("input").val()
if (x >= 1) {
$(this).siblings("input").val(parseInt(x) - parseInt(1));
}
});
// Increment Decrement Buttons End Here
});
Why events are not working? What I am doing wrong/missing here?

i did it by excluding events from $(document).ready();
Then include them in another function and called it from itemsWithAllDetails function at the end.

Related

How do I run code after all threads have finished running?

I have a multithreaded web crawler that downloads a website and stores it in a database (which takes around 4 minutes). To make the crawling faster, I used node.js cluster module, but I have a problem, I want to iterate over to the next segment of the while loop, after all the threads have done their processes, not as soon as they start. How do I make sure all my threads are concluded and then move on?
Here is the relevant code in the main while loop:
while (indexSize !== indexSizeLimit) {
const queueLength = queue.length;
const numberOfThreads = Math.min(numberOfCPUs, queueLength);
const threadAllocations = Array(numberOfThreads).fill(0);
let queuesAllocated = 0;
const queueChunks = [];
function fillQueueChunks() {
loop: while (true) {
for (let i = 0; i < numberOfThreads; i++) {
threadAllocations[i] += 1;
queuesAllocated += 1;
if (queuesAllocated === queueLength) {
break loop;
};
};
};
let start = 0;
for (let threadAllocation of threadAllocations) {
const end = start + threadAllocation;
queueChunks.push(queue.slice(start, end));
start = end;
};
};
fillQueueChunks();
// Find out how to make multithreading finish, and then move on with the loop.
if (cluster.isMaster) {
for (let i = 0; i < numberOfThreads; i++) {
cluster.fork();
};
} else {
const chunk = queueChunks[cluster.worker.id - 1];
await Promise.all(chunk.map(function (url) {
return new Promise(async function (resolve) {
const webcode = await request(url);
if (webcode !== "Failure") {
indexSize += 1;
const document = new Document(url, webcode);
const hrefs = document.hrefs();
const hrefsQuery = Query(hrefs);
// Also make sure it is not included in indexed webpages.
const hrefIndividualized = hrefsQuery.individualize();
hrefIndividualized;
// Do something with hrefIndividualized in regards to maintaining a queue in the database.
// And in adding a nextQueue which to replace the queue in code with.
await document.save();
};
resolve("Written");
});
}));
process.exit(0);
};
};
Wrap the threading in a promise. You can check in the parent thread if there is a disconnect event, and if the amount of disconnects is equal to the number of threads, then you can resolve the promise.
Here is what I have
while (indexSize !== indexSizeLimit) {
let nextQueue = [];
const queueLength = queue.length;
const numberOfThreads = Math.min(numberOfCPUs, queueLength);
const threadAllocations = Array(numberOfThreads).fill(0);
let queuesAllocated = 0;
// queueChunks: [[{_id: ..., ...}], [...], ...]
const queueChunks = [];
function fillQueueChunks() {
loop: while (true) {
for (let i = 0; i < numberOfThreads; i++) {
threadAllocations[i] += 1;
queuesAllocated += 1;
if (queuesAllocated === queueLength) {
break loop;
};
};
};
let start = 0;
for (let threadAllocation of threadAllocations) {
const end = start + threadAllocation;
queueChunks.push(queue.slice(start, end));
start = end;
};
};
fillQueueChunks();
await new Promise(async function (resolve) {
if (cluster.isMaster) {
let threadsDone = 0;
for (let i = 0; i < numberOfThreads; i++) {
cluster.fork();
};
cluster.on("disconnect", function (_) {
threadsDone += 1;
if (threadsDone === numberOfThreads) {
resolve("Queue Processed");
};
});
} else {
const queueJob = queueChunks[cluster.id - 1];
await Promise.all(queueJob.map(function (queueItem) {
return new Promise(async function (resolve) {
const url = queueItem._id;
const webcode = await request(url);
if (webcode !== "Failure") {
const document = Document(url, webcode);
let hrefs = document.hrefs();
const hrefsQuery = Query(hrefs);
await document.save();
indexSize += 1;
hrefs = hrefsQuery.individualize();
const hrefIncidences = Promise.all(hrefs.map(function (href) {
return new Promise(async function (resolve) {
const incidences = await Site.countDocuments({
url: href
});
resolve(incidences);
});
}));
hrefs = hrefs.filter(function (_, i) {
return hrefIncidences[i] === 0;
}).map(function (href) {
return {
_id: href
};
});
await Queue.insertMany(hrefs);
nextQueue = nextQueue.concat(hrefs);
};
await Queue.deleteOne({
_id: url
});
resolve("Success");
});
}));
process.exit(0);
};
});
queue = nextQueue;
};

Maintain counter of a global variable across function

I have a counter which is local to the scope of a parent function and being passed across multiple child functions and is incremented across multiple instances. I am having trouble maintaining the count
I have tried the following
var maxLimit = 150;
async function incrementCounter(counter) {
counter++;
console.log(counter);
return counter;
}
async function processRights() {
var counter = 0,
end = false;
var queryInput = [0, 1, 1, 0, 1];
for (var i = 0; i < queryInput.length; i++) {
var element = queryInput[i];
var thOutput = await processTitle(counter, element, 'th');
if (!thOutput) {
end = true;
return;
}
var nthOutput = await processTitle(counter, element, 'nth');
if (!nthOutput) {
end = true;
return;
};
}
if (!queryInput || !queryInput.length) {
end = true;
}
return;
}
async function processTitle(counter, element, type) {
var output = await callFunc(counter, element, type);
if (!output) {
return false;
}
return output;
}
async function callFunc(counter, element) {
var responses = [];
var counterValue1 = await incrementCounter(counter);
if (counterValue1 >= maxLimit) {
return false;
}
await callAnotherFunc();
if (1) {
var qryArr = [0, 1, 1, 0, 1];
for (let i = 0; i < qryArr.length; i++) {
var counterValue2 = await incrementCounter(counterValue1);
console.log("counterValue2 -- " + counterValue2);
if (counterValue2 >= maxLimit) {
return false;
}
await callAnotherFunc();
}
return responses;
}
}
async callAnotherFunc(){
return true;
}
processRights();
I would like the increment the counter and check against the maximum limit each time the callAnotherFunc function is called. I am a novice to JS. Pl help!
If the counter can be really a global variable, you can declare it side by side with the maxLimit variable, something like this:
var overallCounter = 0;
var maxLimit = 150;
...
async callAnotherFunc(){
return overallCounter++ <= maxLimit;
}
From the question and the code I think this is what you want to achieve, right?

ReferenceError: variable is not define - Node.js

oddsData is undefined when i want to run the code below.
getOdds = async(data) => {
var receivedData = "";
send({"Command":"GetMatchMarkets","Params":data});
var message = JSON.stringify({"Command":"GetMatchMarkets","Params":data});
var length = Buffer.byteLength(message),
buffer = new Buffer(4 + Buffer.byteLength(message));
buffer.writeUInt32LE(length, 0);
buffer.write(message, 4);
client.write(buffer);
var bytesToReceive = length;
var oddsData = "";
client.on('data', async(buf) => {
function calc(){
var offset = 0;
if (bytesToReceive === 0) {
if(buf.length < 4){ return; }
bytesToReceive = buf.readUInt32LE(0);
offset = 4;
}
var currentCommandBytes = Math.min(bytesToReceive, buf.length - offset);
receivedData += buf.slice(offset, offset + currentCommandBytes);
bytesToReceive -= currentCommandBytes;
if (bytesToReceive === 0) {
bytesToReceive = 0;
if (receivedData != ""){
oddsData += receivedData;
}
receivedData = "";
}
if (currentCommandBytes < buf.length - offset) {
calc(buf.slice(currentCommandBytes+offset))
}
}
await calc();
});
console.log(oddsData);
}
return ReferenceError: oddsData is not defined.
oddsData is undefined when i want to run the code below.
Assuming you used oddsData in in your ...OTHER CODES..., maybe the error is due to those nesting of functions,
Declare functions as variables and then pass it to your code.
function test(){
var calc = function (){
...OTHER CODES....
receivedData = "";
return oddsdata
}
var asFun = async (buf) => {
await calc();
}
var oddsData = "";
client.on('data', asFun);
console.log(oddsData);
}
[updated to match changes in question's code]
Stripping out all the code that doesn't affect oddsData leaves the following structure:
const getOdds = async () => {
var oddsData = '';
client.on('data', async () => {
function calc () {
oddsData += 'something';
}
await calc();
});
console.log(oddsData);
};
I see no indication that oddsData should be undefined.
A little test program to explore what's happening:
const getOdds = async() => {
result.innerHTML += 'enter getOdds async()\n';
var oddsData = "";
client.addEventListener('data', async() => {
result.innerHTML += `client.on data async() oddsData: '${oddsData}'\n`;
function calc() {
oddsData += "calc!";
result.innerHTML += `calc() oddsData: '${oddsData}'\n`;
}
await calc();
});
result.innerHTML += `getOdds async() oddsData: '${oddsData}'\n`;
};
window.onload = () => {
result.innerHTML = 'window.onload calling getOdds()\n';
getOdds();
}
<p id="client">This is client.
<button onclick="emitData()">Emit 'data' to client</button>
</p>
<p>Results:</p>
<pre id="result"></pre>
<script>
const client = document.getElementById('client');
const result = document.getElementById('result');
function emitData() {
let event = new Event('data');
client.dispatchEvent(event);
}
</script>

Using a JavaScript function to add data to a string that comes from the HTML document, and preserving that data after that function is called again

I wrote an object called TypeWriter2 and then I want to add it a function called type2().
I then call the TypeWriter2 object using a function called init2(), which queries some data from the html document and passes it to the TypeWriter2 object.
The data that init2() is querying from the html document is:
txtElement2 = a div element, that the type2() function will use to display some data.
words2 = the words that are to be displayed in txtElement2, which is "Hello, there... Yoo"
wait2 = an int that will be passed to setTimeout() later on.
The type2() function is meant is meant of add "iiiiii" to "txt2" (an empty string at the beginning), whenever "txt2" ends with 3 consecutive dots.
The problem being that after "iiiiii" is added to "txt2" and "setTimeout(() => this.type2(), this.wait2);" is called again, "iiiiii" is being deleted from "txt2".
document.addEventListener('DOMContentLoaded', init2);
const TypeWriter2 = function (txtElement2, words2, wait2 = 3000) {
this.txtElement2 = txtElement2;
this.words2 = words2;
this.wait2 = parseInt(wait2, 10);
this.txt2 = '';
this.type2();
}
TypeWriter2.prototype.type2 = function () {
this.txt2 = this.words2.substring(0, this.txt2.length + 1)
if (this.txt2.substr(this.txt2.length - 3) === "...") {
this.txt2 = this.txt2 + "iiiii"
this.txtElement2.innerHTML = `<span class="intro-text">${this.txt2}</span>`;
} else {
this.txtElement2.innerHTML = `<span class="intro-text">${this.txt2}</span>`;
}
setTimeout(() => this.type2(), this.wait2);
}
function init2() {
const txtElement2 = document.querySelector('.intro-text');
const words2 = txtElement2.getAttribute('hello-txt');
const wait2 = txtElement2.getAttribute("data2-wait");
new TypeWriter2(txtElement2, words2, wait2);
}
Thanks in advance!
I was unable to reproduce the bug as described using the posted code, but in all likelihood you can resolve the problem by changing your else statement to an else if such that the type2 method stops being called as soon as all of the text in the "hello-txt" attribute has been added to txtElement2.innerHTML
Attempted repro case: https://jsbin.com/wovatit/1/edit?html,js,output
document.addEventListener('DOMContentLoaded', init2);
const TypeWriter2 = function (txtElement2, words2, wait2 = 3000) {
this.txtElement2 = txtElement2;
this.words2 = words2;
this.wait2 = parseInt(wait2, 10);
this.txt2 = '';
this.type2();
}
TypeWriter2.prototype.type2 = function () {
console.log('called');
this.txt2 = this.words2.substring(0, this.txt2.length + 1)
if (this.txt2.substr(this.txt2.length - 3) === "...") {
this.txt2 = this.txt2 + "iiiii"
this.txtElement2.innerHTML = `<span class="intro-text">${this.txt2}</span>`;
console.log("finished")
} else if(this.txt2.length <= this.words2.length){
this.txtElement2.innerHTML = `<span class="intro-text">${this.txt2}</span>`;
setTimeout(() => this.type2(), this.wait2);
} else{
console.log("finsished")
}
}
function init2() {
const txtElement2 = document.querySelector('.intro-text');
const words2 = txtElement2.getAttribute('hello-txt');
const wait2 = txtElement2.getAttribute("data2-wait");
new TypeWriter2(txtElement2, words2, wait2);
}

Use Promise to get the return data

I am trying to pull the data from realms and then process it using the native call. Once I get the processed data I further filter it in react native code and then give the return data. But till the time I complete all the activity the return parameter is already executed. Please have a look at the below code snippet:
async getArray() {
realm = await this.getRealMObject();
favoriteArray = realm.objects(constants.SCHEMA_SAVE);
return favoriteArray;
}
async getLevel() {
let low = 'false';
let favoriteArray = await this.getAllArray();
let getDetails = [];
if (favoriteArray.length > 0) {
for (var y in favoriteArray) {
NativeModules.Get.GetAsyncTask(
brd[0].toUpperCase(),
strChk, '1',
kResponse => {
if (Platform.OS == 'ios') {
getDetails = kResponse;
} else {
getDetails = JSON.parse(kResponse);
}
for (let x = 0; x < getDetails.length; x++) {
const strLevel = this.getPercentage(getDetails[x]);
if (strLevel <= 20) {
low = true;
}
}
});
}
} else {
low = false;
}
return low;
}
Above is the code snippet. So when I call getlevel() before the processing is finished I get the return low value.
How can I handle, this? I want the data to be processed and then get the return value.

Categories

Resources