Firebase Cloud Function isnt work in Prod. Getting error - javascript

I am getting the following error when going to the URL.
Error: could not handle the request
I can not seem to figure out why. What did I do wrong?
Here is my index.js file.
const functions = require('firebase-functions');
var request = require('request');
const admin = require('firebase-admin');
admin.initializeApp();
exports.addMessage = functions.https.onRequest(async (req, res) => {
const itemDescription = req.query.itemDescription;
const pageNumber = req.query.pageNumber;
const categoryId = req.query.categoryId;
const sortBy = req.query.sortBy;
const narrowSearch = req.query.narrowSearch;
const typeOfListing = req.query.typeOfListing;
const sellerExclusions = req.query.sellerExclusions;
const tagsExclusions = req.query.tagsExclusions;
const country = req.query.country;
const minPrice = req.query.minPrice;
const maxPrice = req.query.maxPrice;
const entriesPerPage = req.query.entriesPerPage;
const buyingFormat = req.query.buyingFormat;
let operationName = "";
let entriesPerPage2 = "";
let sortOrder = "";
let currentPage = "";
if (pageNumber !== null) {
currentPage = pageNumber;
} else {
currentPage = 1;
}
if (typeOfListing === 'active') {
operationName = "findItemsAdvanced";
entriesPerPage2 = 50;
} else {
operationName = "findCompletedItems";
if (buyingFormat === "Auction") {
entriesPerPage2 = 50;
} else {
entriesPerPage2 = 25;
}
}
let apicall = "https://URL?";
if (typeOfListing === "active") {
if (sortBy !== null) {
apicall += "&sortOrder=";
apicall += sortBy;
sortOrder = sortBy;
} else {
apicall += "&sortOrder=";
apicall += "BestMatch";
sortOrder = "BestMatch";
}
} else {
if (sortBy !== null) {
apicall += "&sortOrder=";
apicall += sortBy;
sortOrder = sortBy;
} else {
apicall += "&sortOrder=";
apicall += "EndTimeSoonest";
sortOrder = "EndTimeSoonest";
}
}
if (categoryId !== null) {
apicall += "&categoryId=";
apicall += categoryId;
}
apicall += "&paginationInput.pageNumber=";
apicall += currentPage;
apicall += "&keywords=";
apicall += itemDescription;
apicall += "&paginationInput.entriesPerPage=" + entriesPerPage2;
apicall += "&itemFilter(0).name=SoldItemsOnly&itemFilter(0).value(0)=true";
request(apicall, function (error, response, body) {
if (!error && response.statusCode === 200) {
//here put what you want to do with the request
let paginationOutput = JSON.parse(body).findCompletedItemsResponse[0].paginationOutput;
let pageNumber = null;
let totalPages = null;
let totalEntries = null;
let totalInPage = null;
for (i = 0; i < paginationOutput.length; i++) {
pageNumber = paginationOutput[i].pageNumber[0];
totalPages = paginationOutput[i].totalPages[0];
totalEntries = paginationOutput[i].totalEntries[0];
totalInPage = paginationOutput[i].entriesPerPage[0];
}
let items = JSON.parse(body).findCompletedItemsResponse[0].searchResult[0].item;
let itemId = null;
let title = null;
let categoryId = null;
let categoryName = null;
let galleryURL = null;
let link = null;
let dateEnded = null;
let watchCount = null;
let bestOfferEnabled = null;
let listingType = null;
let soldForOriginal = null;
let timeLeft = null;
let dateLeft = null;
let bidCount = null;
let shipping = null;
//TODO
let soldForBestOffer = null;
var itemArray = {
result: []
};
for (i = 0; i < items.length; i++) {
itemId = items[i].itemId[0];
title = items[i].title[0];
galleryURL = items[i].galleryURL[0];
link = items[i].viewItemURL[0];
category = items[i].primaryCategory;
for (j = 0; j < category.length; j++) {
categoryName = category[j].categoryName[0];
categoryId = category[j].categoryId[0];
}
listingInfo = items[i].listingInfo;
for (k = 0; k < listingInfo.length; k++) {
watchCount = listingInfo[k].watchCount === undefined ? "0" : listingInfo[k].watchCount[0];
bestOfferEnabled = listingInfo[k].bestOfferEnabled[0];
listingType = listingInfo[k].listingType[0];
dateLeft = listingInfo[k].endTime[0];
}
sellingStatus = items[i].sellingStatus;
for (jj = 0; jj < sellingStatus.length; jj++) {
soldForOriginal = sellingStatus[jj].convertedCurrentPrice[0].__value__;
bidCount = sellingStatus[jj].bidCount === undefined ? "0" : sellingStatus[jj].bidCount[0];
timeLeft = sellingStatus[jj].timeLeft === undefined ? "-" : sellingStatus[jj].timeLeft[0];
}
shippingInfo = items[i].shippingInfo;
for (ii = 0; ii < shippingInfo.length; ii++) {
shipping = shippingInfo[ii].shippingServiceCost === undefined ? "0.0" : shippingInfo[ii].shippingServiceCost[0];
shippingType = shippingInfo[ii].shippingType[0];
if (shipping === "0.0") {
shipping = "0.00"
}
if (shippingType === 'Calculated') {
shipping = "TBD";
} else {
if (shipping === '0.00') {
shipping = "FREE";
}
}
}
itemArray.result.push({
"itemId": itemId,
"title": title,
"galleryURL": galleryURL,
"link": link,
"categoryName": categoryName,
"categoryId": categoryId,
"bidCount": bidCount,
"dateEnded": dateLeft,
"watchCount": watchCount,
"bestOfferEnabled": bestOfferEnabled,
"listingType": listingType,
"timeLeft": timeLeft,
"soldForOriginal": soldForOriginal
});
}
res.json({
ack: "success",
message: "results found",
currentPage: pageNumber,
totalPages: totalPages,
totalEntries: totalEntries,
totalInPage: totalInPage,
results: itemArray.result,
searchResult: JSON.parse(body).findCompletedItemsResponse[0].searchResult[0].item
});
} else {
res.json({
error: "didnt work"
});
}
})
});

In Cloud Functions you need to manage asynchronous method calls via Promises. request supports callback interfaces natively but does not return a promise.
You should use another library, like axios, along the following lines:
exports.addMessage = functions.https.onRequest(async (req, res) => {
try {
// ...
let apicall = "https://URL?";
// ...
apicall += "&itemFilter(0).name=SoldItemsOnly&itemFilter(0).value(0)=true";
const response = await axios.get(apicall);
// handle success
// ...
res.json({..});
} catch (error) {
res.status(500).send({ 'error': error });
}
});
Note that you probably need to be on the "Blaze" pricing plan.
As a matter of fact, the free "Spark" plan "allows outbound network requests only to Google-owned services". See https://firebase.google.com/pricing/ (hover your mouse on the question mark situated after the "Cloud Functions" title)
Also note that request is deprecated.

Related

reading from csv file returns undefined value

For some reason, when I am reading a CSV file with React, I am getting undefined as the values, and I am not sure why this is happening. Below is the general format of my .csv file.
Date,Site,Depth (m),Temp (degC),SpeCond(uS/cm),Chla (ug/L),Turb (FTU),DO (mg/L)
Mar-18-2019,UA01,-0.518,10.9387,233.3824,4.2043,11.118,10.7842
Mar-18-2019,UA01,-0.585,10.9352,233.4042,4.4753,11.272,10.7935
Mar-18-2019,UA01,-0.651,10.9335,233.3973,4.641,11.26,10.7987
Mar-18-2019,UA01,-0.717,10.9319,233.4335,4.7184,10.985,10.796
Mar-18-2019,UA01,-0.785,10.9292,233.4137,4.8404,10.985,10.7938
Mar-18-2019,UA01,-0.85,10.9268,233.4009,5.0127,11.158,10.7885
Mar-18-2019,UA01,-0.909,10.9257,233.4585,5.1674,11.662,10.78
Mar-18-2019,UA01,-0.969,10.9248,233.4452,5.3253,11.249,10.7753
Mar-18-2019,UA01,-1.04,10.9241,233.3777,5.5321,10.852,10.7706
...
This is my App.js:
import React,{useState} from "react";
import * as $ from 'jquery';
import ReactDOM from 'react-dom'
import Highcharts from 'highcharts';
export default function App() {
const [selects, setSelects] = useState();
return (
<div className="App">
<h1>{selects}</h1>
<h3 className = "form-labels"> Visuals: </h3>
<select value = {selects} onChange = {e=>printSelected(e.target.value) }>
<option>Temperature</option>
<option>Special Conductivity</option>
<option>Chlorophyll</option>
<option>Turbosity</option>
<option>Dissolved Oxygen</option>
</select>
<select value = {selects} onChange = {e=>printSelected1(e.target.value) }>
<option>UA01</option>
<option>UA01_SB19</option>
<option>UA01_SB25</option>
<option>UA06</option>
<option>UA06_SB19</option>
<option>UA06_SB25</option>
<option>UA07</option>
<option>UA07_SB19</option>
<option>UA07_SB25</option>
<option>UA08</option>
<option>UA08_SB19</option>
<option>UA08_SB25</option>
<option>LA03</option>
<option>LA03_SB19</option>
<option>LA03_SB25</option>
<option>NR02</option>
<option>NR02_SB19</option>
<option>NR02_SB25</option>
<option>OA04</option>
<option>OA04_SB19</option>
<option>OA04_SB25</option>
</select>
</div>
);
}
const x = [];
const y = [];
var tab = [];
var tab1 = [];
var tab2 = [];
var tab3 = [];
var tab4 = [];
var response = "";
var data = "";
var sortedD = [];
var sortedD1 = [];
var sortedD2 = [];
var sortedD3 = [];
var sortedD4 = [];
var fileName = "UA01";
var visuals = "Temp";
function printSelected(e) {
sortedD.length = 0;
tab.length = 0;
sortedD1.length = 0;
tab1.length = 0;
sortedD2.length = 0;
tab2.length = 0;
sortedD3.length = 0;
tab3.length = 0;
sortedD4.length = 0;
tab4.length = 0;
visuals = e;
getChart();
}
function printSelected1(e) {
sortedD.length = 0;
tab.length = 0;
sortedD1.length = 0;
tab1.length = 0;
sortedD2.length = 0;
tab2.length = 0;
sortedD3.length = 0;
tab3.length = 0;
sortedD4.length = 0;
tab4.length = 0;
fileName = e;
getChart();
}
async function getChart() {
await getData();
var data1 = [];
var name1 = "";
if (visuals.localeCompare("Temp") === 0) {
data1 = sortedD;
name1 = "Temperature (deg Celsius) ";
} else if (visuals.localeCompare("Special Conductivity") === 0) {
data1 = sortedD1;
name1 = "Special Conductivity (uS/cm) ";
} else if (visuals.localeCompare("Chlorophyll") === 0) {
data1 = sortedD2;
name1 = "Chlorophyll (ug/L) ";
} else if (visuals.localeCompare("Turbosity") === 0) {
data1 = sortedD3;
name1 = "Turbosity (FTU) ";
} else {
data1 = sortedD4;
name1 = "Dissolved Oxygen (mg/L)";
}
}
async function getData() {
response = await fetch(fileName + ".csv");
data = await response.text();
const table = data.split('\n').slice(1);
table.forEach(row => {
const col = row.split(',');
const depth = col[2];
var ele = [];
var ele1 = [];
var ele2 = [];
var ele3 = [];
var ele4 = [];
console.log("Depth: " + depth);
console.log("Val: " + col[3]);
ele.push(parseFloat(col[3]));
ele.push(parseFloat(depth));
ele1.push(parseFloat(col[4]));
ele1.push(parseFloat(depth));
ele2.push(parseFloat(col[5]));
ele2.push(parseFloat(depth));
ele3.push(parseFloat(col[6]));
ele3.push(parseFloat(depth));
ele4.push(parseFloat(col[7]));
ele4.push(parseFloat(depth));
tab.push(ele);
tab1.push(ele1);
tab2.push(ele2);
tab3.push(ele3);
tab4.push(ele4);
})
sortedD = tab.sort((a,b) => b[0]-a[0]);
sortedD1 = tab1.sort((a,b) => b[0]-a[0]);
sortedD2 = tab2.sort((a,b) => b[0]-a[0]);
sortedD3 = tab3.sort((a,b) => b[0]-a[0]);
sortedD4 = tab4.sort((a,b) => b[0]-a[0]);
}
getChart();
I am trying to build a dropdown menu to display different line graphs depending on what dropdown is selected, but for some reason when I try to print values of my variables I am trying to plot, I get undefined. And the length of the arrays I have made are always 43 for some reason...
Depth: undefined
Val: undefined
Depth: undefined
Val: undefined
Depth: undefined
Val: undefined
Depth: undefined
Val: undefined
Depth: undefined
Val: undefined
Depth: undefined
I have a feeling that it might be the await fetch and await response, but I am not 100% sure. Any tips on this would be greatly appreciated!

Why is insert operation slower than search/delete in Binary Search Tree, considering that all should be around O(logn)

I've implemented BST to compare to others objects types, as Map, {} and Array.
But the weird thing is that insertion in BST takes too long, but search and delete operations in BST is faster than in any other data type.
I'm guessing that is due to many instances of Node, but i don't even sure if that makes sense..
export class BinarySearchTree{
constructor(root = null){
this.root = root;
this.length = 1;
}
search(key){
let cur_node = this.root;
while(true){
if(cur_node === null || cur_node === undefined) return null;
if(cur_node.key === key) return cur_node;
if(key < cur_node.key) cur_node = cur_node.left;
else cur_node = cur_node.right;
}
}
add(key, value = key){
const new_node = new Node(key, value);
let cur_node = this.root;
let parent_node = null;
if(!this.root){
this.root = new_node;
return;
}
while(true){
if(cur_node === null) break;
parent_node = cur_node;
if(parent_node.key === key) return;
if(key < cur_node.key) cur_node = cur_node.left;
else cur_node = cur_node.right;
}
const side = key < parent_node.key ? 'left' : 'right';
parent_node[side] = new_node;
this.length++;
}
delete(key){
let cur_node = this.root;
let parent_node = null;
while(true){
if(cur_node === null || cur_node.key === key) break;
parent_node = cur_node;
if(key < cur_node.key) cur_node = cur_node.left;
else cur_node = cur_node.right;
}
let children = cur_node.getChildren();
const side = parent_node !== null ? parent_node.getChildByKey(key)[0] : 'root';
if(children.length === 0) parent_node[side] = null;
else if(children.length === 1) parent_node[side] = children[0][1];
else if(children.length === 2){
const min_node_map = this.minNode(cur_node.right);
cur_node.key = min_node_map.get('min').key;
cur_node.value = min_node_map.get('min').value;
min_node_map.get('parent').left = null;
}
this.length--;
}
minNode(node = this.root){
let parent_node = null;
let cur_node = node;
while(cur_node.left) {
parent_node = cur_node;
cur_node = cur_node.left;
}
const map = new Map();
map.set('min', cur_node);
map.set('parent', parent_node);
return map;
}
}
export class Node{
constructor(key, value){
this.key = key;
this.value = value;
this.left = null;
this.right = null;
}
getChildByKey(key){
return this.getChildren().find(x => x[1].key === key);
}
getChildren(){
const map = new Map();
map.set('left', this.left);
map.set('right', this.right);
return [...map].filter(x => x[1] !== null);
}
}
import { BinarySearchTree } from "./binary-search-tree.js";
const INTERACTIONS = 999999;
//random keys
const random_values = new Array(INTERACTIONS);
for(let i = 0; i < INTERACTIONS; i++)random_values[i] = random(0, INTERACTIONS);
//just to test SEARCH
const SPECIAL_KEY = 1234567;
random_values[Math.floor((random_values.length - 1)/2)] = SPECIAL_KEY;
const item = 'any constant data';
const show = () => {
let arr = [];
console.log('array');
performance('insert', () => {
for(let i = 0; i < INTERACTIONS; i++)
arr.push(random_values[i])
});
performance('search', () => arr.find(x => x === SPECIAL_KEY));
performance('delete', () => arr.splice(arr.indexOf(SPECIAL_KEY), 1));
const obj = {};
console.log(`obj`);
performance('insert', () => {
for(let i = 0; i < INTERACTIONS; i++)
obj[random_values[i]] = item
});
performance('search', () => obj[SPECIAL_KEY]);
performance('delete', () => delete obj[SPECIAL_KEY]);
const map = new Map();
console.log(`map`);
performance('insert', () => {
for(let i = 0; i < INTERACTIONS; i++)
map.set(random_values[i], item)
});
performance('search', () => map.get(SPECIAL_KEY));
performance('delete', () => map.delete(SPECIAL_KEY));
const bst = new BinarySearchTree();
console.log(`binary search tree`);
performance('insert', () => {
for(let i = 0; i < INTERACTIONS; i++)
bst.add(random_values[i], item)
});
performance('search', () => bst.search(SPECIAL_KEY).value);
performance('delete', () => bst.delete(SPECIAL_KEY));
}
show();
function random(min, max){
return Math.floor(Math.random() * (max - min) + min);
}
function performance(title, callback){
const start_time = process.hrtime();
callback();
const end_time = process.hrtime(start_time);
console.log(`${title} ending... ${end_time} seconds`);
}

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>

javascript multiple function callback syntax

I can't wrap my head around callback syntax, can you please help me re-write my code so that it executes in this order:
MenuBuilder.load()
MenuBuilder.draw()
Translator.load()
(in my case it executes in this order MenuBuilder.load(), Translator.load(), MenuBuilder.draw() so it doesn't do what I want)
onload.js
import MenuBuilder from "./menu-builder.js";
import Translator from "./translator.js";
var menuBuilder = new MenuBuilder();
var translator = new Translator();
menuBuilder.load();
translator.load();
menu-builder.js
"use strict"
class MenuBuilder {
constructor() {
this._nav = document.getElementsByTagName("nav")[0];
this._url = window.location.href;
}
load() {
console.log("MenuBuilder.load() start");
fetch(`/json/menu.json`)
.then((res) => res.json())
.then((jsonMenu) => {
this.draw(jsonMenu);
})
/*.catch(() => {
console.error(`Could not load ${this._lang}.json.`);
});*/
console.log("MenuBuilder.load() end");
}
draw(jsonMenu) {
console.log("MenuBuilder.draw(jsonMenu) start");
var htmlMenu = `<div id="siteTitleDiv"><p id="siteTitle" data-i18n="general.title"></p><p id="siteTitleShadow" data-i18n="general.title-shadow"></p><p id="siteSubtitle"data-i18n="general.subtitle"></p></div><ul>`;
for(var i = 0; i < jsonMenu.length; i++) {
var menuItem = jsonMenu[i];
var regexp = /http:\/\/cypher-f\.com\/(([a-z\-]*\/)?([a-z\-]*\/))?/g;
var fullPage = "something format_abc";
var match = regexp.exec(this._url);
var level_1 = match[1];
var level_2 = match[3];
var parent = match[2];
var full_suffix = match[0];
if ((parent == null) || (menuItem.parent === parent)) {
var material_icon = menuItem["material-icon"];
var href = menuItem["href"];
var i18n = menuItem["data-i18n"];
htmlMenu += `<li><i class="material-icons">${material_icon}</i></li>`;
}
}
htmlMenu += `</ul>`;
this._nav.innerHTML = htmlMenu;
console.log("MenuBuilder: nav.innerHTML");
console.log(this._nav.innerHTML);
console.log("MenuBuilder: document.elements");
console.log(document.querySelectorAll("[data-i18n]"));
console.log("MenuBuilder.draw(jsonMenu) end");
}
}
export default MenuBuilder;
translator.js
"use strict"
class Translator {
constructor() {
this._lang = this.getLanguage();
this._elements = document.querySelectorAll("[data-i18n]");
}
getLanguage() {
var lang = navigator.languages ? navigator.languages[0] : navigator.language;
return lang.substr(0, 2);
}
load(lang = null) {
console.log("Translator.load() start");
console.log("this._elements");
console.log(this._elements);
if (lang) {
this._lang = lang;
}
else {
var re = new RegExp("lang=([^;]+)");
var value = re.exec(document.cookie);
var cookieLang = (value != null) ? unescape(value[1]) : null;
if (cookieLang) {
this._lang = cookieLang;
}
}
fetch(`/i18n/${this._lang}.json`)
.then((res) => res.json())
.then((translation) => {
this.translate(translation);
})
.then(this.toggleLangTag())
.then(document.cookie = `lang=${this._lang};path=/`)
/*.catch(() => {
console.error(`Could not load ${this._lang}.json.`);
});*/
console.log("Translator.load() end");
}
translate(translation) {
console.log("Translator.load(translation) start");
this._elements.forEach((element) => {
var keys = element.dataset.i18n.split(".");
var text = keys.reduce((obj, i) => obj[i], translation);
if (text) {
element.innerHTML = text;
}
else {
element.innerHTML = `key ${keys} not found for ${this._lang}!`
}
});
console.log("Translator.load(translation) end");
}
toggleLangTag() {
if (document.documentElement.lang !== this._lang) {
document.documentElement.lang = this._lang;
}
}
switchLanguage(translator) {
var availableLang = ["en", "fr"];
var currentLangIndex = availableLang.indexOf(translator._lang);
var nextLang = availableLang[(currentLangIndex + 1)%availableLang.length];
translator.load(nextLang);
}
}
export default Translator;
I'm sorry I know this is kind of a newbie question but I haven't programmed in three years.
You're working with Promises here, so you want to stick with that paradigm. Return the promise that is returned from the fetch call, then "chain" off of that promise to call the translator.
load() {
console.log("MenuBuilder.load() start");
// The return here gives control of the promise to the caller...
return fetch(`/json/menu.json`)
.then((res) => res.json())
.then((jsonMenu) => {
this.draw(jsonMenu);
})
/*.catch(() => {
console.error(`Could not load ${this._lang}.json.`);
});*/
console.log("MenuBuilder.load() end");
}
So back in onload.js you can use the promise returned from menuBuilder.load() to call translator.load() after menuBuilder.load() is done.
import MenuBuilder from "./menu-builder.js";
import Translator from "./translator.js";
var menuBuilder = new MenuBuilder();
var translator = new Translator();
menuBuilder.load().then(() => translator.load());

Return object from function to which JSON is passed

Dears,
I have a function, to which i input JSON data
function getTotals(users){
users = data;
allUsers = users.length;
active = 0;
women = 0;
men = 0;
lastActive = 0;
for (elm in users){
if (users[elm].active){
active++;
if (users[elm].gender == "Female"){
women++;
} else if (users[elm].gender == "Male") {
men++;
} else if (users[elm].last_login){
var lastLogin = new Date (users[elm].last_login);
var lastMonths = lastLogin.getMonth()-6;
var lastYears = lastLogin.getFullYear();
//console.log(lastYears);
if (lastMonths <6 && lastMonths > -6 && lastYears >= lastLogin.getFullYear()-1){
lastActive++;
}
}
}
}
return {allUsers : allUsers, active : active, women : women, men : men, lastActive : lastActive};}
but i cannot display the values, when i do following:
var listOfUsers = document.createElement('p');
listOfUsers.textContent = "Liczba wszystkich użytkowników: "+allUsers;
document.querySelector("#row1 > div").appendChild(listOfUsers);
var listOfActive = document.createElement('p');
listOfActive.textContent = "Liczba aktywnych użytkowników: "+active;
document.querySelector("#row2 > div").appendChild(listOfActive);
var listOfWomen = document.createElement('p');
listOfWomen.textContent = "Liczba aktywnych kobiet: "+women;
document.querySelector("#row3 > div").appendChild(listOfWomen);
var listOfMen = document.createElement('p');
listOfMen.textContent = "Liczba aktywnych mężczyzn: "+men;
document.querySelector("#row4 > div").appendChild(listOfMen);
var listOfLastActv = document.createElement('p');
listOfLastActv.textContent = "Liczba aktywnych (ost 6 mcy): "+lastActive;
document.querySelector("#row5 > div").appendChild(listOfLastActv);
When i do following (found here in other questions):
var getTotalUsers = new getTotal();
var allUsers = getTotalUsers.allUsers;
var active = getTotalUsers.active;
var women = getTotalUsers.women;
var men = getTotalUsers.men;
var lastActive = getTotalUsers.lastActive;
I get undefined as a result. I do not know how to fix this issue, as in next part of js, i will need to display list of active users.
new Promise() returns results asynchronously. You can either chain .then() or use async/await to get expected result
function httpGet() {
return new Promise(function(resolve) {
setTimeout(function() {
resolve([{a:1}, {b:2}, {c:3}])
}, Math.floor(Math.random() * 1200))
})
}
async function getTotals() {
const users = await httpGet();
console.log(users);
}
getTotals();
function httpGet() {
return new Promise(function(resolve) {
setTimeout(function() {
resolve([{a:1}, {b:2}, {c:3}])
}, Math.floor(Math.random() * 1200))
})
}
function getTotals() {
const data = httpGet();
data.then(function(users) {
console.log(users)
})
.catch(function(err) {
console.log(err)
})
}
getTotals();

Categories

Resources