Async call in javascript For Loop not working - javascript

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...
})

Related

Value of Variable within Function NOT Changing when using If Statement in HTTP GET Request

I have a variable called
let idStatus = '';
I need my getValues function to return true and am using this variable to determine whether it returns true or false.
function getValues(){
let idStatus = '';
let getValuesUrl = 'https://something.something.com/v1.0/something/1?apiKey=1234abcdefghijklmnop';
const getValuesRequest = new XMLHttpRequest();
getValuesRequest.responseType = 'json';
getValuesRequest.open('GET', getOptionValuesUrl);
getValuesRequest.send();
getValuesRequest.onreadystatechange = function () {
const response = getValuesRequest.response;
if (response) {
if (getValuesRequest.status == 200) {
console.log('Success');
if(validateIds(response)){
console.log('ID is Valid');
idStatus = true;
}
else {
console.log('ID is NOT Valid');
idStatus = false;
}
}
}
console.log(idStatus);
return idStatus;
}
function validateIds(obj) {
const data = obj['data'];
console.log(data);
let validId = '';
for (let i = 0; i < data.length; i++) {
if (data[i].id == 1) {
validId = true;
}
else {
validId = false;
}
}
console.log(validId);
return validId;
}
Valid IDs runs the way it should and getValues console.logs the appropriate responses when it is true or false, yet idStatus always returns null.
Here I've made a simpler version of your code. I used axios instead of XMLHttpRequest as it's simpler to use.
const axios = require("axios");
async function getValues(link) {
const response = await axios.get(link);
if (!response.statusCode == 200) return false;
if (response.data.some(elm => elm.id != 1)) return false;
return true;
}
// if the status isn't 200, return false;
if (!response.statusCode == 200) return false;
// if one id isn't 1, return false;
if (response.data.some(elm => elm.id != 1)) return false;
If you want more details on Array.some(), here's a link Array.Some()

Unable to return result from promise

I am trying to read some data from 2 different tables and parse a CSV file before rendering an ejs file.
I can get the data from both tables and from the CSV file but I seem to be unable to return the result.
Pretty sure this is a problem with the way I handle async execution but I fail to see what I am doing wrong.
I've spent the last 2 days reading about this (including the threads around here) and browsing but somehow the answer still escapes me.
First file - usercms.js
app.get('/userscms', function(req, res)
{
existingUsers.getExistingUsers()
.then(function(appUsers)
{
//global users array
//I can display these in my ejs file
globalAppUsers = appUsers;
})
.then(existingUsersAttributesQlik.getExistingUsersAttributesQlik())
.then(function(usersQlikAttributes)
{
//global user attributes array
//undefined data
globalUsersQlikAttributes = usersQlikAttributes;
})
.then(existingSuppliers.parseSuppliersCSV())
.then(function(supplierData)
{
//the result I am expecting
//this prints undefined
console.log(supplierData);
}).then(function()
{
res.render('userscms.ejs',
{
users: globalAppUsers,
attributes: globalUsersQlikAttributes
});
});
});
Second function - getxistingUsers.js (identical to the getExistingUsersAttributesQlik, except for the query)
var userData = [];
var appUsers = [];
(function (exports)
{
exports.getExistingUsers = function ()
{
return promisemysql.createConnection(dbconfig.development).then(function(conn)
{
var result = conn.query("SELECT id, username, firstName, lastName, email, phone, lastLogin, isAdmin, isValid, isPhoneValid, accountCreationDateTime FROM Users");
conn.end();
return result;
}).then(function(rows)
{
return rows;
}).then(function(rows)
{
if (rows.length)
{
userData = [];
appUsers = [];
rows.forEach(function (elem)
{
userData.push(_.toArray(elem));
});
for (i = 0; i < userData.length; i++)
{
var appUser = new appUserModel.AppUser(
userData[i][0],
userData[i][1],
userData[i][2],
userData[i][3],
userData[i][4],
userData[i][5],
userData[i][6],
userData[i][7],
userData[i][8],
userData[i][9],
userData[i][10]);
appUsers.push(_.toArray(appUser));
}
return appUsers;
}
else
{
console.log("NOPE");
return null;
}
}).then(function(appUsers)
{
console.log(appUsers);
return appUsers;
});
};
})(typeof exports === 'undefined' ? this['getExistingUsers'] = {} : exports);
Third file - parseSuppliersCSV.js
var supplierData = [];
var suppliersData = [];
var csvCount = 0;
(function (exports)
{
exports.parseSuppliersCSV = function ()
{
return new Promise(function(resolve, reject)
{
var fileStream = fs.createReadStream("myCSV.csv");
var parser = fastCsv();
csvCount = 0;
supplierData = [];
suppliersData = [];
fileStream
.on("readable", function ()
{
var data;
while ((data = fileStream.read()) !== null)
{
parser.write(data);
}
})
.on("end", function ()
{
parser.end();
});
parser
.on("readable", function ()
{
var data;
while ((data = parser.read()) !== null)
{
if(csvCount >= 1)
{
csvCount++;
var arrayOfStrings = data[0].split(';');
var supplier = new supplierModel.Supplier(arrayOfStrings[0],arrayOfStrings[1]);
suppliersData.push(_.toArray(supplier));
}
else
{
csvCount++;
}
}
})
.on("end", function ()
{
console.log("done");
//all OK here
console.log(suppliersData);
//this doesn't seem to return anything
return suppliersData;
});
});
};
})(typeof exports === 'undefined' ? this['parseSuppliersCSV'] = {} : exports);
Any ideas what I am doing wrong? Am I approaching this the wrong way?
I'll take a guess here and assume the promise you created should resolve to something...instead of returning a value.
.on("end", function ()
{
console.log("done");
//all OK here
console.log(suppliersData);
//this doesn't seem to return anything
return resolve(suppliersData);
});

How to access object array using javascript with variable

var dict = {
"configMigratedTo": {
"message": "Migrated configuration to configurator: $1"
}
}
var parametersForTranslation = {};
function __tr(src, params) {
parametersForTranslation[src] = params;
return buildMessage(src);
}
function buildMessage(src){
var message=dict[src] ? dict[src].message : src
console.log(message);
var messageArray = message.split("$");
var output = "";
messageArray.forEach(function(elem, index){
if(index === 0){
output += elem;
}else{
// get variable and index
var paramIndex = configMigratedTo.substring(0, 1);
var paramValue = parametersForTranslation[src][paramIndex-1];
output += paramValue;
output += configMigratedTo.substring(1);
}
});
return output;
}
__tr("configMigratedTo", [2]);
console.log(buildMessage("configMigratedTo"));
i want get result like __tr("configMigratedTo", [2]);
then it will give me
Migrated configuration to configurator: 2
i do not know where is wrong in my code
Try this one. Hope it helps!
var dict = {
"configMigratedTo": {
"message": "Migrated configuration to configurator: $1"
}
}
function __tr(src, params)
{
for (var key in dict)
{
if (key === src)
{
var message = dict[key].message;
return message.substring(0, message.length - 2) + params[0];
}
}
return;
}
console.log(__tr("configMigratedTo", [2]))
https://jsfiddle.net/eLd9u2pq/
Would that be enought?
var dict = {
"configMigratedTo": {
"message": "Migrated configuration to configurator: "
}
}
function buildMessage(src,param){
var output = dict[src].message + param;
return output;
}
console.log(buildMessage("configMigratedTo",2));
You are overcomplicating this, it's much easier using a regex and passing a function as replacer
var dict = {
"configMigratedTo": {
"message": "Migrated configuration to configurator: $1"
}
}
function __tr(src, params) {
if (! dict[src]) return src;
if (! /\$0/.test(dict[src].message)) params.unshift('');
return dict[src].message.replace(/\$(\d)+/g, (orig, match) => params[match] || orig);
}
console.log(__tr("configMigratedTo", [2]));

How to pass an array from one function to another as reference in Cloud Function

I have one function getUsers where I have one array jsonResponse. I am passing that array to computeData function. I want computeData function should be able to add items in jsonResponse array itself.
But below code is not adding in same array, as it always return empty array in response.send function.
index.js
exports.getUsers = functions.https.onRequest((request, response) => {
var x = [];
var xLocation,
yLocation = [],
jsonResponse = [];
// print algorithm name
console.log(request.query.algo);
let geoFire = new GeoFire(db.ref("/users/" + request.query.userId));
geoFire.get("location").then(function(location) {
xLocation = location;
});
db
.ref("/users/" + request.query.userId)
.once("value")
.then(function(snapshot) {
var jsonObject = snapshot.val();
var basicProfileJsonObject = jsonObject.basicProfile;
for (var key in basicProfileJsonObject) {
if (utils.isNumber(basicProfileJsonObject[key])) {
x.push(basicProfileJsonObject[key]);
}
}
db.ref("/users/").once("value").then(function(snapshot) {
var y = [];
snapshot.forEach(function(item) {
var user = item.val();
let userId = user.basicProfile.userId;
if (userId !== request.query.userId) {
if (xLocation == null) {
computeData(x, user, request.query.algo, jsonResponse);
} else {
let geoFire = new GeoFire(db.ref("/users/" + userId));
geoFire.get("location").then(function(location) {
if (location === null) {
console.log(
"Provided key is not in GeoFire, will ignore profile"
);
computeData(x, user, request.query.algo, jsonResponse);
} else {
console.log("Provided key has a location of " + location);
var distance = GeoFire.distance(xLocation, location); // in km
console.log("Distance: " + distance);
if (distance < 15) {
computeData(x, user, request.query.algo, jsonResponse);
}
}
});
}
}
});
response.send(jsonResponse);
});
});
});
function computeData(x, user, algo, jsonResponse) {
var similarityCount,
y = [];
var basicProfileJsonObject = user.basicProfile;
for (var key in basicProfileJsonObject) {
if (utils.isNumber(basicProfileJsonObject[key])) {
y.push(basicProfileJsonObject[key]);
}
}
if (algo === "cosine") {
// compute cosine value
similarityCount = cosineUtils.cosineSimilarity(x, y);
} else if (algo == "euclidean") {
// compute euclidean distance value
similarityCount = 1 / (1 + euclidean(x, y));
} else if (algo === "pearson-correlation") {
// compute pearson correlation coefficents
similarityCount = pcorr.pearsonCorrelation(x, y);
}
console.log(x);
console.log(y);
console.log(similarityCount);
jsonResponse.push(user);
}
Does anyone know how to pass array as reference and add items into it in Cloud Function for Firebase ?
Your else statement is a promise which means your loop would have finished and called response.send(jsonResponse); by the time it gets to computeData() in your else statement.
Try something like this, it doesn't touch all your variables but the main idea is to use Promise.all with computed values as resolved -
exports.getUsers = functions.https.onRequest((request, response) => {
// blah blah
var y = []; // store promises that resolves your computed value
snapshot.forEach(function(item) {
// blah blah
if (xLocation == null) {
y.push(Promise.resolve(computeData());
} else {
y.push(computeAnotherData(userId));
}
});
Promise.all(y)
.then(values => {
response.send(values);
});
});
function computeAnotherData(userId) {
let geoFire = new GeoFire(db.ref("/users/" + userId));
return geoFire.get("location").then(function(location) {
return computeData();
});
}
Hope it makes sense.

How can Actionhero receive the parameter without inputs defined?

I'm using ActionHero in node.js and Angular.js.
I am trying images send to ActionHero using $http method.
but I don't know How many images are made.
so I can't define the parameter names on action in ActionHero.
below is my source.
First. images are in object, so I change object to each parameter.
insert: function (param, next) {
var url = settings.apiUrl + "/api/online/productAdd";
var vdata = {
img_objects :param.img_objects
};
angular.forEach(param.img_objects, function (v, k) {
vdata['img_file'+(k)] = v.files;
});
commonSVC.sendUrlFile("POST", url, vdata, function (state, data) {
next(state, data);
});
}
Second. make formData in sendUrlFile like source below. and then send to actionHero.
var promise = $http({
method: method,
url: url,
headers: {
'Content-Type': undefined
},
data: params,
transformRequest: function (data) {
var formData = new FormData();
angular.forEach(data, function (value, key) {
if(angular.isObject(value)){
if(value.lastModified > 0 && value.size > 0){
formData.append(key, value);
}else{
formData.append(key, JSON.stringify(value));
}
}else{
formData.append(key, value);
}
});
return formData;
}
});
Third. ActionHero is received. but parameter isn't defined so ActionHero can't receive.
exports.productAdd = {
name: 'online/productAdd',
inputs: {
I don't know How Many Images are made? 1~10? or 1~100?
},
authenticate: true,
outputExample: {
'result':'success'
}
So I have two Questions:
How can actionhero receive the parameter without inputs defined?
Can I object with Image Data send to ActionHero by Ajax?
Thank You.
I change reduceParams function in actionProcessor.js.
api.actionProcessor.prototype.reduceParams = function(){
var self = this;
var inputNames = [];
if(self.actionTemplate.inputs){
inputNames = Object.keys(self.actionTemplate.inputs);
}
// inputs * 확인 2017-01-20 Eddy
var multi = [];
var strArray;
for(var v in inputNames){
if(inputNames[v].indexOf("*") != -1){
strArray = inputNames[v].split('*');
multi.push(strArray[0]);
}
}
var multiLength = multi.length;
var flag;
if(api.config.general.disableParamScrubbing !== true){
for(var p in self.params){
flag = true;
if(multiLength > 0){
for(var i=0; i<multiLength; i++){
if(p.indexOf(multi[i]) != -1){
flag = false;
}
}
}
if(flag){
if(api.params.globalSafeParams.indexOf(p) < 0 && inputNames.indexOf(p) < 0){
delete self.params[p];
}
}
}
}
};
i can define on inputs like below.
'img_*' : {required: false}
and Then I make middleware
var actionHeroMiddleware = {
name: '-',
global: true,
priority: 1000,
preProcessor: function(data, next) {
api.actionProcessor.prototype.reduceParams = function(){
var self = this;
var inputNames = [];
if(self.actionTemplate.inputs){
inputNames = Object.keys(self.actionTemplate.inputs);
}
// inputs * 확인 2017-01-20 Eddy
var multi = [];
var strArray;
for(var v in inputNames){
if(inputNames[v].indexOf("*") != -1){
strArray = inputNames[v].split('*');
multi.push(strArray[0]);
}
}
var multiLength = multi.length;
var flag;
if(api.config.general.disableParamScrubbing !== true){
for(var p in self.params){
flag = true;
if(multiLength > 0){
for(var i=0; i<multiLength; i++){
if(p.indexOf(multi[i]) != -1){
flag = false;
}
}
}
if(flag){
if(api.params.globalSafeParams.indexOf(p) < 0 && inputNames.indexOf(p) < 0){
delete self.params[p];
}
}
}
}
};
next();
},
stop: function(api, next) {
next();
}
};
api.actions.addMiddleware(actionHeroMiddleware);
next();

Categories