Can't get `count` from Asynchronous function - javascript

I have the below code where d3.json is an asynchronous function. I am trying to run it in a loop while my count is equal to 100. My while loop stops after the first iteration, because the count is happening inside the asynchronous function, so I don't run it as many times as I should. How can I get the correct count so my while loop keeps executing while keeping the asynchronous trait?
$(document).ready(function() {
$('button').click(function() {
var start = new Date().getTime();
while(count == 100){
console.log("first iteration");
count = 0;
d3.json("/api/messages/" + offset, function(error, json) {
if (error) return console.warn(error);
data = json;
for(var i = 0; i < data.messages.length; i++){
console.log(data.messages[i].date);
count++;
console.log(count);
}
});
offset += 100;
}
var end = new Date().getTime();
var time = end - start;
console.log("Time to execute : " + time);
});
});
EDIT: I'm trying for my calls to be as shown below. At each call you would check and make sure that there are 100 items(count) returned , and if not, you would stop the while loop
/api/messages/0
/api/messages/100
/api/messages/200
/api/messages/300
/api/messages/400
/api/messages/500
/api/messages/600

Here is how I would do it:
Create a function that accepts the relevant parameters: start offset, increment, and most importantly a done callback that should execute in the end.
This function contains a worker function, which will call the API, check the result and either call itself, or the done callback:
function fetchAllMessages(start, increment, done) {
var messages = [];
(function nextCall(offset) {
d3.json("/api/messages/" + offset, function (error, data) {
if (error) return done(error, messages);
if (!data.messages) return done("unexpected response format", messages);
messages.push.apply(messages, data.messages);
if (data.messages.length === increment) {
nextCall(offset + increment);
} else {
done(null, messages);
}
});
})(start);
}
Now you can use it simply from your click event handler:
$(function() {
$('button').click(function() {
var start = Date.now();
fetchAllMessages(0, 100, function (err, messages) {
var end = Date.now();
if (err) console.warn(err);
console.log(messages);
console.log("Time to execute : " + (start - end));
});
});
});

The idea is to chain this ajax calls until a certain cut-off point is reach (in this example offset is greater than max).
I have changed the d3.json call to jQuery.getJSON for this answer as its easier to debug on jsfiddle, but the concept is exactly the same. I also had to change the url for the request to use the jsfiddle debug api.
var start = new Date().getTime();
var offset = 0;
var maxOffset = 600;
var baseUrl = "/echo/json"; // change this to /api/messages in production
var callback = function(json) {
console.log(json);
console.log("current offset: " + offset);
data = json;
// ... do something with data ...
// increment the offset
offset += 100;
// don't run any more and return the execution time
if (offset > maxOffset) {
var end = new Date().getTime();
var time = end - start;
console.log("Time to execute : " + time);
return; // don't run any more
}
// offset too small so run another getJSON call with our callback
$.getJSON(baseUrl + "?" + offset, callback);
}
// when button is click, start the json call chain
$('button').click(function() {
// change the "?" to "/" in production
$.getJSON(baseUrl + "?" + offset, callback);
});
If you need help translating this to your exact problem let me know.
Here is the jsfiddle.

Related

Javascript decrement from 10 then do something when 0

I have a function that when called will decrease by 1. It is called when a user reports something. I want to be able to store this and then when it hits 0, to execute an action.
function userReported() {
console.log('user report ' + add());
var add = (function () {
var counter = 10;
return function () {
counter -= 1;
return counter;
}
})();
}
Now the problem is I can return the counter so it logs down from 10. But the issue I have is that I can seem to add an if/else before returning counter as it does not store the variable.
I attempted the following but it doesn't work and I don't know how to return something > store it, and at the same time check its value. I also tried a while loop but failed too.
function userReported() {
var limit = add;
if ( limit <= 0 ) {
console.log('Link does not work!');
}
else {
console.log('user report ' + limit);
}
var add = (function () {
var counter = 10;
return function () {
counter -= 1;
return counter;
}
})();
}
How do I go about creating a value, increment/decrement said value, then when it reaches a number -> do something?
You would typically do this with a function that returns a function that captures the counter in a closure. This allows the returned function to maintain state over several calls.
For example:
function createUserReport(limit, cb) {
console.log('user report initiated' );
return function () {
if (limit > 0) {
console.log("Report filed, current count: ", limit)
limit--
} else if (limit == 0) {
limit--
cb() // call callback when done
}
// do something below zero?
}
}
// createUserReport takes a limit and a function to call when finished
// and returns a counter function
let report = createUserReport(10, () => console.log("Reached limit, running done callback"))
// each call to report decrements the limit:
for (let i = 0; i <= 10; i++){
report()
}
You can of course hard-code the callback functionality and limit number into the function itself rather than passing in arguments.
Ok, if you need to get a report based on an external limit, you could do something like that:
var limit = 10;
function remove() {
limit -= 1;
}
function userReport() {
if (limit <= 0) {
console.log("Link does not work!");
} else {
remove();
console.log(`User report: ${limit}`);
}
}
userReport();
If that's what you want, removing the remove function from userReport and taking the limit variable out will make things work

Incrementing a counter in recursive function calls

I'm struggling on how to increment a basic counter in javascript.
What do I want to achieve ?
I need a counter inside a foreach loop. The goal is to be able to count each time the //Write smthg is triggered.
Below is the updated version of the code I'm using. For the moment, it returns weird sequences of numbers. I guess it is resetted each time the recursive loop is triggered. I do not know how to correct it, suppose it's a basic javascript problem but as I'm learning through experimenting and on my own, I sometimes need to ask question to the community.
function walk(dir, counter = 0) {
fs.readdirSync(dir).forEach(file => {
let fullPath = path.join(dir, file);
if (fs.lstatSync(fullPath).isDirectory()) {
counter = walk(fullPath, counter);
walk(fullPath, counter);
console.log('dir');
} else {
let size = fs.statSync(fullPath).size; // Get size of file
listFiles.write(fullPath + " (" + size + ")\n"); // Write file path and size into copyList.xml
++counter;
console.log(counter);
}
});
return counter;
}
walk(copyFrom); // Starts function "walk"
Sequences obtained :
2,3,4,5,6,7,dir,5,6,8,9,10,11,12,13,dir,11
Here is the complete answer
function walk(dir) {
let n = 0;
function walk(dir) {
fs.readdirSync(dir).forEach(file => {
++n;
console.log(n);
let fullPath = path.join(dir, file);
if (fs.lstatSync(fullPath).isDirectory()) {
--n;
walk(fullPath);
console.log('dir');
} else {
let size = fs.statSync(fullPath).size; // Get size of file
listFiles.write(fullPath + " (" + size + ")\n"); // Write file path and size into copyList.xml
}
});
}
return walk(dir);
}
Use a helper. The function walk makes the lexical variable n and a function walk that shadows the called fucntion for the duration of the recursive calls. It may have the original content of walk and the outer function just returns the result of calling it as itself was called.
function walk(dir) {
let n = 0; //Counter variable
function walk(dir) {
dir.forEach(file => {
++n;
console.log(n);
if (true) {
//Recurse loop
} else {
//Write smthg
}
});
}
return walk(dir);
}
So, your issue is as follows:
Your counter will reset to 0 each time you recurse. So your numbers can go something like so: 0, 1, 0, 2, 0, 1, 2, 3, 3, ...etc. If you want to have an iterator counting total number of iterations, you'll need to pass your counter into the function and default it to 0 (for the first time walk is called), like so:
var files = ["dir1-file1", "dir1-file2", ["dir1-sub1-file1"], "dir1-file3", ["dir1-sub2-file1", ["dir1-sub2-subsub1-file1"]]];
function walk(dir, counter = 0) {
dir.forEach(file => {
if (Array.isArray(file)) {
// pass counter in to recursed function call
// set current function counter to the result of the recursed function calls
counter = walk(file, counter);
} else {
//Write smthg
++counter;
console.log(counter);
console.log(file);
}
});
// return the counter for parent
return counter;
}
walk(files);

Nodejs: Getting average number of requests

I need to send X requests to http://date.jsontest.com/ where X is an argument to my program. I've managed to get the latency for one request but now need to calculate the average time in milliseconds for multiple requests. I have an array responseTimes[] where I'd like to store the response times. How do I possibly add the multiple response times and get the average? Any help? Do I need to use the setTimeout function in the first place?
I'm using node v8.9.4 if fetchURL does not work on your end.
Here's my code
var fetchUrl = require("fetch").fetchUrl;
fetchUrl("http://date.jsontest.com", function(error, meta, body){
const start = new Date();
const responseTimes = [];
let count = 0;
setTimeout(function (argument) {
// execution time simulated with setTimeout function
var end = new Date() - start;
console.log("Execution time: %dms", end);
});
});
You need to put the start variable outside the request.
var fetchUrl = require("fetch").fetchUrl;
var start = new Date();
fetchUrl("http://date.jsontest.com", function(error, meta, body){
const requests = [];
let count = 0;
// execution time simulated with setTimeout function
var end = new Date() - start;
console.log("Execution time: %dms", end);
});
If you're storing responseTime[] then with that you can store count of requests. So at any point in time, you can get average by the following function -
function getAvg(timeArr, count){
let sum = 0;
for(let i=0; i<timeArr.length; i++){
sum += timeArr[i];
}
return sum/count;
}
Also, It's not necessary to store responseTime[]. You can just calculate avg on each request and store only the average and count If you just need average.
var fetchUrl = require("fetch").fetchUrl;
let responseTime = [];
let count = 0;
fetchUrl("http://date.jsontest.com", function(error, meta, body){
const start = new Date();
const requests = [];
let count = 0;
setTimeout(function (argument) {
// execution time simulated with setTimeout function
var end = new Date() - start;
console.log("Execution time: %dms", end);
responseTime.push(end);
count++;
let averageNow = getAvg(responseTime, count);
console.log(averageNow);// this is your average
});
});
You can use Artillery npm module to get the average response time of an API.

Multiple queries in a loop Parse Cloud Code

I'm having a hard time trying to understand promises, I'm sure I need to use them for this but I don't know how and other answers don't help me at all.
I'd like to loop over an array, query all the results for each value of the array, then after calculating the average value for these results, add the average in an array. After every iterations, this array is sent as a response.
Here is my code which could help understand me here:
Parse.Cloud.define('getScorePeopleArray', function(request, response) {
var peopleArray = request.params.peoplearray;
var query = new Parse.Query("Scores");
var resultat;
var index, len;
var resultarray = [];
var people;
for (index = 0, len = peopleArray.length; index < len; ++index) {
people = peopleArray[index];
query.equalTo("People",people);
query.find({
success: function(results) {
var sum = 0;
for (var i = 0; i < results.length; ++i) {
sum += results[i].get("Score");
}
resultat = (sum / results.length)*5;
if(!resultat){
resultarray.push("null");
}else{
resultarray.push(resultat);
}
},
error: function() {
response.error("score lookup failed");
}
}).then();
}
response.success(resultarray);
});
Of course response.success is not called when every queries are done, but as soon as possible (since queries are asynchronous if I'm right).
I know I have to change it with promises, but I don't understand at all how this works.
Thanks a lot in advance !
var _ = require('underscore');
Parse.Cloud.define('getScorePeopleArray', function(request, response) {
var peopleArray = request.params.peoplearray; // what is this an array of?
var resultArray = [];
return Parse.Promise.as().then(function() { // this just gets the ball rolling
var promise = Parse.Promise.as(); // define a promise
_.each(peopleArray, function(people) { // use underscore, its better :)
promise = promise.then(function() { // each time this loops the promise gets reassigned to the function below
var query = new Parse.Query("Scores");
query.equalTo("People", people); // is this the right query syntax?
return query.find().then(function(results) { // the code will wait (run async) before looping again knowing that this query (all parse queries) returns a promise. If there wasn't something returning a promise, it wouldn't wait.
var sum = 0;
for (var i = 0; i < results.length; i++) {
sum += results[i].get("Score");
}
var resultat = (sum / results.length) * 5;
if (!resultat){
resultArray.push("null");
} else {
resultArray.push(resultat);
}
return Parse.Promise.as(); // the code will wait again for the above to complete because there is another promise returning here (this is just a default promise, but you could also run something like return object.save() which would also return a promise)
}, function (error) {
response.error("score lookup failed with error.code: " + error.code + " error.message: " + error.message);
});
}); // edit: missing these guys
});
return promise; // this will not be triggered until the whole loop above runs and all promises above are resolved
}).then(function() {
response.success(resultArray); // edit: changed to a capital A
}, function (error) {
response.error("script failed with error.code: " + error.code + " error.message: " + error.message);
});
});

How do I measure the execution time of JavaScript code with callbacks?

I have a piece of JavaScript code that I am executing using the node.js interpreter.
for(var i = 1; i < LIMIT; i++) {
var user = {
id: i,
name: "MongoUser [" + i + "]"
};
db.users.save(user, function(err, saved) {
if(err || !saved) {
console.log("Error");
} else {
console.log("Saved");
}
});
}
How can I measure the time taken by these database insert operations? I could compute the difference of date values after and before this piece of code but that would be incorrect because of the asynchronous nature of the code.
Use the Node.js console.time() and console.timeEnd():
var i;
console.time("dbsave");
for(i = 1; i < LIMIT; i++){
db.users.save({id : i, name : "MongoUser [" + i + "]"}, end);
}
end = function(err, saved) {
console.log(( err || !saved )?"Error":"Saved");
if(--i === 1){
console.timeEnd("dbsave");
}
};
There is a method that is designed for this. Check out process.hrtime(); .
So, I basically put this at the top of my app.
var start = process.hrtime();
var elapsed_time = function(note){
var precision = 3; // 3 decimal places
var elapsed = process.hrtime(start)[1] / 1000000; // divide by a million to get nano to milli
console.log(process.hrtime(start)[0] + " s, " + elapsed.toFixed(precision) + " ms - " + note); // print message + time
start = process.hrtime(); // reset the timer
}
Then I use it to see how long functions take. Here's a basic example that prints the contents of a text file called "output.txt":
var debug = true;
http.createServer(function(request, response) {
if(debug) console.log("----------------------------------");
if(debug) elapsed_time("recieved request");
var send_html = function(err, contents) {
if(debug) elapsed_time("start send_html()");
response.writeHead(200, {'Content-Type': 'text/html' } );
response.end(contents);
if(debug) elapsed_time("end send_html()");
}
if(debug) elapsed_time("start readFile()");
fs.readFile('output.txt', send_html);
if(debug) elapsed_time("end readFile()");
}).listen(8080);
Here's a quick test you can run in a terminal (BASH shell):
for i in {1..100}; do echo $i; curl http://localhost:8080/; done
Invoking console.time('label') will record the current time in milliseconds, then later calling console.timeEnd('label') will display the duration from that point.
The time in milliseconds will be automatically printed alongside the label, so you don't have to make a separate call to console.log to print a label:
console.time('test');
//some code
console.timeEnd('test'); //Prints something like that-> test: 11374.004ms
For more information, see Mozilla's developer docs on console.time.
Surprised no one had mentioned yet the new built in libraries:
Available in Node >= 8.5, and should be in Modern Browers
https://developer.mozilla.org/en-US/docs/Web/API/Performance
https://nodejs.org/docs/latest-v8.x/api/perf_hooks.html#
Node 8.5 ~ 9.x (Firefox, Chrome)
// const { performance } = require('perf_hooks'); // enable for node
const delay = time => new Promise(res=>setTimeout(res,time))
async function doSomeLongRunningProcess(){
await delay(1000);
}
performance.mark('A');
(async ()=>{
await doSomeLongRunningProcess();
performance.mark('B');
performance.measure('A to B', 'A', 'B');
const measure = performance.getEntriesByName('A to B')[0];
// firefox appears to only show second precision.
console.log(measure.duration);
// apparently you should clean up...
performance.clearMarks();
performance.clearMeasures();
// Prints the number of milliseconds between Mark 'A' and Mark 'B'
})();
https://repl.it/#CodyGeisler/NodeJsPerformanceHooks
Node 12.x
https://nodejs.org/docs/latest-v12.x/api/perf_hooks.html
const { PerformanceObserver, performance } = require('perf_hooks');
const delay = time => new Promise(res => setTimeout(res, time))
async function doSomeLongRunningProcess() {
await delay(1000);
}
const obs = new PerformanceObserver((items) => {
console.log('PerformanceObserver A to B',items.getEntries()[0].duration);
// apparently you should clean up...
performance.clearMarks();
// performance.clearMeasures(); // Not a function in Node.js 12
});
obs.observe({ entryTypes: ['measure'] });
performance.mark('A');
(async function main(){
try{
await performance.timerify(doSomeLongRunningProcess)();
performance.mark('B');
performance.measure('A to B', 'A', 'B');
}catch(e){
console.log('main() error',e);
}
})();
For anyone want to get time elapsed value instead of console output :
use process.hrtime() as #D.Deriso suggestion, below is my simpler approach :
function functionToBeMeasured() {
var startTime = process.hrtime();
// do some task...
// ......
var elapsedSeconds = parseHrtimeToSeconds(process.hrtime(startTime));
console.log('It takes ' + elapsedSeconds + 'seconds');
}
function parseHrtimeToSeconds(hrtime) {
var seconds = (hrtime[0] + (hrtime[1] / 1e9)).toFixed(3);
return seconds;
}
var start = +new Date();
var counter = 0;
for(var i = 1; i < LIMIT; i++){
++counter;
db.users.save({id : i, name : "MongoUser [" + i + "]"}, function(err, saved) {
if( err || !saved ) console.log("Error");
else console.log("Saved");
if (--counter === 0)
{
var end = +new Date();
console.log("all users saved in " + (end-start) + " milliseconds");
}
});
}
Old question but for a simple API and light-weight solution; you can use perfy which uses high-resolution real time (process.hrtime) internally.
var perfy = require('perfy');
function end(label) {
return function (err, saved) {
console.log(err ? 'Error' : 'Saved');
console.log( perfy.end(label).time ); // <——— result: seconds.milliseconds
};
}
for (var i = 1; i < LIMIT; i++) {
var label = 'db-save-' + i;
perfy.start(label); // <——— start and mark time
db.users.save({ id: i, name: 'MongoUser [' + i + ']' }, end(label));
}
Note that each time perfy.end(label) is called, that instance is auto-destroyed.
Disclosure: Wrote this module, inspired by D.Deriso's answer. Docs here.
You could also try exectimer. It gives you feedback like:
var t = require("exectimer");
var myFunction() {
var tick = new t.tick("myFunction");
tick.start();
// do some processing and end this tick
tick.stop();
}
// Display the results
console.log(t.timers.myFunction.duration()); // total duration of all ticks
console.log(t.timers.myFunction.min()); // minimal tick duration
console.log(t.timers.myFunction.max()); // maximal tick duration
console.log(t.timers.myFunction.mean()); // mean tick duration
console.log(t.timers.myFunction.median()); // median tick duration
[edit] There is an even simpler way now to use exectime. Your code could be wrapped like this:
var t = require('exectimer'),
Tick = t.Tick;
for(var i = 1; i < LIMIT; i++){
Tick.wrap(function saveUsers(done) {
db.users.save({id : i, name : "MongoUser [" + i + "]"}, function(err, saved) {
if( err || !saved ) console.log("Error");
else console.log("Saved");
done();
});
});
}
// Display the results
console.log(t.timers.myFunction.duration()); // total duration of all ticks
console.log(t.timers.saveUsers.min()); // minimal tick duration
console.log(t.timers.saveUsers.max()); // maximal tick duration
console.log(t.timers.saveUsers.mean()); // mean tick duration
console.log(t.timers.saveUsers.median()); // median tick duration
You can use a wrapper function to easily report the execution time of any existing function.
A wrapper is a used to extend an existing function to do something before and after the existing function's execution - and is a convenient way to compose logic.
Here is an example of using the withDurationReporting wrapper:
// without duration reporting
const doSomethingThatMayTakeAWhile = async (someArg: string, anotherArg: number) => {
/** your logic goes here */
}
// with duration reporting
const doSomethingThatMayTakeAWhileWithReporting = withDurationReporting(
'doSomethingThatMayTakeAWhile',
doSomethingThatMayTakeAWhile
);
// note: you can define the function with duration reporting directly, too
const doSomethingThatMayTakeAWhile = withDurationReporting(
'doSomethingThatMayTakeAWhile',
async (someArg: string, anotherArg: number) => {
/** your logic goes here */
}
)
And here is the wrapper itself:
import { hrtime } from 'process';
const roundToHundredths = (num: number) => Math.round(num * 100) / 100; // https://stackoverflow.com/a/14968691/3068233
/**
* a wrapper which reports how long it took to execute a function, after the function completes
*/
export const withDurationReporting = <R extends any, T extends (...args: any[]) => Promise<R>>(
title: string,
logic: T,
options: {
reportingThresholdSeconds: number;
logMethod: (message: string, metadata?: Record<string, any>) => void;
} = {
reportingThresholdSeconds: 1, // report on anything that takes more than 1 second, by default
logMethod: console.log, // log with `console.log` by default
},
) => {
return (async (...args: Parameters<T>): Promise<R> => {
const startTimeInNanoseconds = hrtime.bigint();
const result = await logic(...args);
const endTimeInNanoseconds = hrtime.bigint();
const durationInNanoseconds = endTimeInNanoseconds - startTimeInNanoseconds;
const durationInSeconds = roundToHundredths(Number(durationInNanoseconds) / 1e9); // https://stackoverflow.com/a/53970656/3068233
if (durationInSeconds >= options.reportingThresholdSeconds)
options.logMethod(`${title} took ${durationInSeconds} seconds to execute`, { title, durationInSeconds });
return result;
}) as T;
};
I designed a simple method for this, using console.time() & console.timeEnd():
measure function definition
function measureRunningTime(func,...args){
const varToString = varObj => Object.keys(varObj)[0]
const displayName = func.name || varToString({ func })
console.time(displayName)
func(...args)
console.timeEnd(displayName)
}
To use it, pass a function without arguments, with arguments binded, or with arguments as the following parameters.
Examples:
let's say I want to check the running time of the simplest searching algorithm - SimpleSearch:
measured function definition (your code here)
const simpleSearch = (array = [1,2,3] ,item = 3) => {
for(let i = 0; i< array.length; i++){
if (array[i] === item) return i;
}
return -1
}
implementation without arguments
measureRunningTime(simpleSearch)
//Prints something like that-> simpleSearch: 0.04ms
implementation with arguments using .bind()
const array = [1,2,3]
const item = 3
measureRunningTime(simpleSearch.bind(null, array, item))
//Prints something like that-> bound simpleSearch: 0.04ms
implementation with arguments without using .bind()
const array = [1,2,3]
const item = 3
measureRunningTime(simpleSearch, array, item)
//Prints something like that-> simpleSearch: 0.04ms
-> Take notice!! this implementation is far from perfect - for example there is no error handling - but it can be used to check the running times of simple algorithms,
Moreover , I'm not an experienced programmer so take everything with a grain of salt 🧂 👌
I had same issue while moving from AWS to Azure
For express & aws, you can already use, existing time() and timeEnd()
For Azure, use this:
https://github.com/manoharreddyporeddy/my-nodejs-notes/blob/master/performance_timers_helper_nodejs_azure_aws.js
These time() and timeEnd() use the existing hrtime() function, which give high-resolution real time.
Hope this helps.
I need this to be cumulative, and to measure different stuff.
Built these functions:
function startMeasuring(key) {
measureTimers[key] = process.hrtime();
}
function stopMeasuring(key) {
if (!measures[key]) {
measures[key] = 0;
}
let hrtime = process.hrtime(measureTimers[key]);
measures[key] += hrtime[0] + hrtime[1] / 1e9;
measureTimers[key] = null;
}
Usage:
startMeasuring("first Promise");
startMeasuring("first and second Promises");
await new Promise((resolve) => {
setTimeout(resolve, 1400);
});
stopMeasuring("first Promise");
stopMeasuring("first and second Promises");
startMeasuring("first and second Promises");
await new Promise((resolve) => {
setTimeout(resolve, 600);
});
stopMeasuring("first and second Promises");
console.log("Measure Results", measures);
/*
Measusre Results {
setting: 0.00002375,
'first Promise': 1.409392916,
'first and second Promise': 2.015160376
}
*/

Categories