why does the data couldn't show in the viewpage? - javascript

this is the html code:
<li ng-repeat="data in spreadGroupData" ng-click="channelList(data.campaigns,data.name)">{{data.name}}</li>`
this is the code i write in the services.js:
services.getChannelName = function($scope,channelidList){
httpurl = "api/account/"+nowuID+"/channel/channellist?id=" + channelidList;
$http.get(httpurl).success(function(data){
if(data.length>0){
$scope.spreadGroupData = [];
for(var i in data){
var group = {};
group.campaigns = data[i].id;
group.name = data[i].name;
$scope.spreadGroupData.push(group);
}
}
});
};
there are data in $scope.spreadGroupData,why couldn't show in the view page?
Now I know I shouldn't use $scope in the service,but the param 'channelidList' I get it from another service method. How to rewrite this all?
services.getListData = function(scope,flag){
var reportList = "quality_report",merger = true;
if(typeof flag!='undefined' && flag == 1){
reportList = "fakequality_report";
merger = false;
}
var cids = scope.spreadUrls,dateArr=scope.date.split(" - "),startDate = "",endDate = "",channelids = "";
if(dateArr.length==1){
startDate = endDate = dateArr[0];
}else{
startDate = dateArr[0];
endDate = dateArr[1];
}
if(cids!=null){
if(cids!='All'){
channelids = "&channelid="+cids.join(",");
}
if(scope.selecteds != -1 && typeof(scope.selecteds) != "undefined"){
httpurl = "api/app/"+scope.selecteds+"/report/"+reportList+"?startdate="+startDate+"&enddate="+endDate+channelids;
$http.get(httpurl).success(function(data,status){
scope.tabTitle = data.name;
var tableList = services.colToRow(data.val),cidlen = cids.length;
scope.tabTotal = services.dataToTotal(data.val,cidlen);
var key = data.key,tabname = [],zero = [],tabListInfo = [],allnames = scope.spreadNames;
for(var i=0;i<scope.tabTotal.length;i++){
zero[i] = 0;
}
for(i=0;i<cidlen;i++){
var idx = $.inArray(allnames[i],key);
tabListInfo[i] = new Array();
if(idx>-1){
tabListInfo[i] = tableList[idx];
}else{
tabListInfo[i] = zero;
}
if(merger){
var temp = [];
for(var j=0;j<tabListInfo[i].length;j++){
temp[j] = tabListInfo[i][j];
}
temp.unshift(scope.spreadNames[i]);
tabListInfo[i] = temp;
}
}
var channelIdList = [];
if(key.length>0){
var n = 0;
for(var i in scope.spreadData){
for(var j in key){
if(key[j] == scope.spreadData[i].name){
n++;
channelIdList.push(scope.spreadData[i].channel);
if(n>20) break;
}
}
}
}
services.getChannelName(scope,channelIdList.join(","));
scope.tabname = scope.spreadNames;
if(merger){
var tabListObj = [];
if(reportList == "quality_report"){
for(var i = 0; i <tabListInfo.length; i++){
tabListObj.push({
"name" : tabListInfo[i][0],
"hitNum" : tabListInfo[i][1],
"reSchedulNum" : tabListInfo[i][2],
"activeDevice" : tabListInfo[i][3],
"activeRate" : tabListInfo[i][4],
"payment" : tabListInfo[i][5],
"spdID" : cids[i]
});
}
}
scope.tabListInfo = tabListObj;
}else{
if(reportList == "fakequality_report"){
var tabListObj = [];
for(var i = 0; i <tabListInfo.length; i++){
tabListObj.push({
"name" : scope.tabname[i],
"reSchedulNum" : tabListInfo[i][0],
"hitNum" : tabListInfo[i][1],
"errHitNum" : tabListInfo[i][2],
"errHitRate" : tabListInfo[i][3],
"activeDevice" : tabListInfo[i][4],
"errActDevice" : tabListInfo[i][5],
"errActRate" : tabListInfo[i][6],
"spdID" : cids[i]
});
}
scope.tabListInfo = tabListObj;
}else{
scope.tabListInfo = tabListInfo;
}
}
scope.spreadIDs = cids;
}).error(function(data){
services.loginTimeout(data);
});
}
}
};

You should never pass $scope object to service, service should always have a reusable method which will exposed. I'd suggest you service method should return promise to the controller caller method, and caller method will implement the binding logic inside controller promise success method.
Service Method
services.getChannelName = function(channelidList) {
httpurl = "api/account/" + nowuID + "/channel/channellist?id=" + channelidList;
return $http.get(httpurl).success(function(data) {
return data;
}).error(function(err) {
return err;
});
};
Controller Method
$scope.getChannelName = function() {
$scope.spreadGroupData = [];
service.getChannelName(channelidList).then(function(data) {
if (data.length > 0) {
for (var i in data) {
var group = {};
group.campaigns = data[i].id;
group.name = data[i].name;
$scope.spreadGroupData.push(group);
}
}
}, function(err) {
console.log("Error" + err);
})
}
Update
Whole idea about the code like below. Need to maintain proper code stack resolve.
First service method will return promise, on resolved of it you need to do change in some scope variables, then you will call second service method which has promise, on resolved of it you need to update scope.
Code
services.getListData(flag).then(function(data) { //you may need to pass multiple parameter to this
//then do scope operation
service.getChannelName(channelidList).then(function(res) {
if (res.length > 0) {
for (var i in data) {
var group = {};
group.campaigns = data[i].id;
group.name = data[i].name;
$scope.spreadGroupData.push(group);
}
}
}, function(err) {
console.log("Error" + err);
});
})

I only saw one little thing that might be cause a problem, there is a missing var keyword in front of the httpurl variable and I only add that to below demo.
The view you need to show your data:
<body ng-controller="myController">
Spread Group Data
<br />
------------------------------------------------------------
<li ng-repeat="data in spreadGroupData"
ng-click="channelList(data.campaigns,data.name)">
{{data.name}}
</li>
</body>
I used a mock json provide to simulate your service and call it in a controller directly:
// Prepared a mock json array on the http://beta.json-generator.com and below url returns:
// [{"name":"Item 1","id":1},{"name":"Item 2","id":2},{"name":"Item 3","id":3},{"name":"Item 4","id":4}]
var httpurl = "http://beta.json-generator.com/api/json/get/LoUmNC4";
$http.get(httpurl).success(function(data) {
if (data.length > 0) {
$scope.spreadGroupData = [];
for (var i in data) {
var group = {};
group.campaigns = data[i].id;
group.name = data[i].name;
$scope.spreadGroupData.push(group);
}
}
});
If your service is independent from your controller, then you can pass $scope to your service method. But in this demo I implemented the http call block directly in a main controller. Besides this as #pankajparkar's said do not use the $scope in factories or service unrelated services and take and use response data from that like services. Please check promise and $q in order to handle asynchronous calls.
This is a working demo: Demo

Place $scope.spreadGroupData = []; outside $http call :-
services.getChannelName = function($scope,channelidList){
httpurl = "api/account/"+nowuID+"/channel/channellist?id=" + channelidList;
$scope.spreadGroupData = [];
$http.get(httpurl).success(function(data){
if(data.length>0){
for(var i in data){
var group = {};
group.campaigns = data[i].id;
group.name = data[i].name;
$scope.spreadGroupData.push(group);
}
}
});
};

Related

Error with setTimeout() function in for loop

I have the following script that I need to adjust so that each iteration has a one second pause before or after it executes the loop (it doesn't really matter which as long as the lag is there). I tried to add the setTimeout() function into the Try section of my code but it is still consistently failing. I also have tried to use "let" instead of "var" in the for loop but that failed as well. Any advice on how to add it in would be very appreciated. I'm having trouble finding an example of a similar setTimeout() function within a for loop online.
var ZB_DataExtension = 'C7_Unsubscribe_Response';
var ZB_DataExtension_Response = 'C7_Unsubscribe_Response';
var ZB_DataExtension_Logs = 'C7_CustUnsubscribe_Logs';
//Endpoint
var zeroBounceFullUrl = 'https://api.commerce7.com/v1//customer/CUST_ID';
//Extract results from Data Extension using DE key
var results = DataExtension.Init(ZB_DataExtension).Rows.Retrieve();
var updateDE_ZB = DataExtension.Init(ZB_DataExtension_Response);
var logsDE_ZB = DataExtension.Init(ZB_DataExtension_Logs);
var today = Format(Now(), "YYYY-MM-DD ");
for (var i = 0; i < results.length; i++ ) {
var item = results[i];
var zeroBounceUrlItem = "";
var ZB_Status = "";
var currentDateTime = Now();
try{
setTimeout(() => (
zeroBounceUrlItem = String(zeroBounceFullUrl).split("CUST_ID").join(String(item.C7_CustID));
var req = new Script.Util.HttpRequest(zeroBounceUrlItem);
req.emptyContentHandling = 0;
req.retries = 3;
req.continueOnError = true;
req.contentType = "application/json";
req.method = "PUT";
var payload='{"emailMarketingStatus": "Unsubscribed"}'
req.postData = payload ;
var resp = req.send();
var returnStatus= resp.returnStatus;
updateDE_ZB.Rows.Update({C7_API_Answer:String(returnStatus),ValidationDate:currentDateTime,ValidationUrl:String(zeroBounceUrlItem),EmailAddress:String(item.EmailAddress)}, ["C7_CustID"], [String(item.C7_CustID)]);
if (returnStatus==0) {
updateDE_ZB.Rows.Update({C7_API_Answer:String("Success"),ValidationDate:currentDateTime,ValidationUrl:String(zeroBounceUrlItem),EmailAddress:String(item.EmailAddress)}, ["C7_CustID"], [String(item.C7_CustID)]);
}
else {
//ZB_Status = String("ERRO ZB API Call");
//var responseJson = Platform.Function.ParseJSON(String(resp.content));
updateDE_ZB.Rows.Update({C7_API_Answer:String("Failure"),ValidationDate:currentDateTime,ValidationUrl:String(zeroBounceUrlItem),EmailAddress:String(item.EmailAddress)}, ["C7_CustID"], [String(item.C7_CustID)]);
}
var randomID = Platform.Function.GUID();
logsDE_ZB.Rows.Add({log_guid:String(randomID),C7_CustID:String(item.C7_CustID),Status:String("Success"),ValidationDate:currentDateTime,ValidationUrl:String(zeroBounceUrlItem)});
), 1000*i}
catch (err) {
var randomID = Platform.Function.GUID();
ZB_Status = String("ERRO AMPScript");
logsDE_ZB.Rows.Add({log_guid:String(randomID),C7_CustID:String(item.C7_CustID),Status:String("Failure"),ValidationDate:currentDateTime,ValidationUrl:String(zeroBounceUrlItem)});
}
}
</script>
Your loop will execute the right number of times and at the right interval, but the value of the variable item inside the timeout might not be what you expect.
Try this:
for (var i = 0; i < results.length; i++ ) {
(function(i){
setTimeout(function(){
var item = results[i];
var zeroBounceUrlItem = "";
var ZB_Status = "";
var currentDateTime = Now();
try{
zeroBounceUrlItem = String(zeroBounceFullUrl).split("CUST_ID").join(String(item.C7_CustID));
var req = new Script.Util.HttpRequest(zeroBounceUrlItem);
req.emptyContentHandling = 0;
req.retries = 3;
req.continueOnError = true;
req.contentType = "application/json";
req.method = "PUT";
var payload='{"emailMarketingStatus": "Unsubscribed"}'
req.postData = payload ;
var resp = req.send();
var returnStatus= resp.returnStatus;
updateDE_ZB.Rows.Update({C7_API_Answer:String(returnStatus),ValidationDate:currentDateTime,ValidationUrl:String(zeroBounceUrlItem),EmailAddress:String(item.EmailAddress)}, ["C7_CustID"], [String(item.C7_CustID)]);
if (returnStatus==0) {
updateDE_ZB.Rows.Update({C7_API_Answer:String("Success"),ValidationDate:currentDateTime,ValidationUrl:String(zeroBounceUrlItem),EmailAddress:String(item.EmailAddress)}, ["C7_CustID"], [String(item.C7_CustID)]);
}
else {
//ZB_Status = String("ERRO ZB API Call");
//var responseJson = Platform.Function.ParseJSON(String(resp.content));
updateDE_ZB.Rows.Update({C7_API_Answer:String("Failure"),ValidationDate:currentDateTime,ValidationUrl:String(zeroBounceUrlItem),EmailAddress:String(item.EmailAddress)}, ["C7_CustID"], [String(item.C7_CustID)]);
}
var randomID = Platform.Function.GUID();
logsDE_ZB.Rows.Add({log_guid:String(randomID),C7_CustID:String(item.C7_CustID),Status:String("Success"),ValidationDate:currentDateTime,ValidationUrl:String(zeroBounceUrlItem)});
catch (err) {
var randomID = Platform.Function.GUID();
ZB_Status = String("ERRO AMPScript");
logsDE_ZB.Rows.Add({log_guid:String(randomID),C7_CustID:String(item.C7_CustID),Status:String("Failure"),ValidationDate:currentDateTime,ValidationUrl:String(zeroBounceUrlItem)});
}
}, i*1000);
})(i);
}

JavaScript Web Resource issue: getGrid() suddenly started failing

I have a few different JavaScript web resources that use the getGrid(), all of which started failing this week after I enabled the 2020 Wave 1 Updates in D365. The error message shows:
"Error occurred :TypeError: Unable to get property 'getGrid' of undefined or null reference"
Here is my code:
function GetTotalResourceCount(executionContext) {
console.log("function started");
var execContext = executionContext;
var formContext = executionContext.getFormContext();
var resourceyescount = 0;
try {
var gridCtx = formContext._gridControl;
var grid = gridCtx.getGrid();
var allRows = grid.getRows();
var duplicatesFound = 0;
//loop through rows and get the attribute collection
allRows.forEach(function (row, rowIndex) {
var thisRow = row.getData().entity;
var thisRowId = thisRow.getId();
var thisResource = "";
var thisResourceName = "";
var thisResourceID = "";
console.log("this row id=" + thisRowId);
var thisAttributeColl = row.getData().entity.attributes;
thisAttributeColl.forEach(function (thisAttribute, attrIndex) {
var msg = "";
if (thisAttribute.getName() == "new_resource") {
thisResource = thisAttribute.getValue();
thisResourceID = thisResource[0].id;
thisResourceName = thisResource[0].name;
console.log("this resource name=" + thisResourceName)
}
});
var allRows2 = formContext.getGrid().getRows();
//loop through rows and get the attribute collection
allRows2.forEach(function (row, rowIndex) {
var thatRow = row.getData().entity;
var thatRowId = thatRow.getId();
var thatAttributeColl = row.getData().entity.attributes;
var thatResource = "";
var thatResourceName = "";
var thatResourceID = "";
thatAttributeColl.forEach(function (thatAttribute, attrIndex) {
if (thatAttribute.getName() == "new_resource") {
thatResource = thatAttribute.getValue();
thatResourceID = thatResource[0].id;
thatResourceName = thatResource[0].name;
if (thatResourceID == thisResourceID && thatRowId != thisRowId) {
duplicatesFound++;
var msg = "Duplicate resource " + thatResource;
console.log("duplicates found= " + duplicatesFound);
}
}
});
});
});
if (duplicatesFound > 0) {
console.log("duplicate found");
Xrm.Page.getAttribute("new_showduplicateerror").setValue(true);
Xrm.Page.getControl("new_showduplicateerror").setVisible(true);
Xrm.Page.getControl("new_showduplicateerror").setNotification("A duplicate resource was found. Please remove this before saving.");
} else {
Xrm.Page.getAttribute("new_showduplicateerror").setValue(false);
Xrm.Page.getControl("new_showduplicateerror").setVisible(false);
Xrm.Page.getControl("new_showduplicateerror").clearNotification();
}
} catch (err) {
console.log('Error occurred :' + err)
}
}
Here is a separate web resource that triggers the function:
function TriggerSalesQDResourceCount(executionContext){
var formContext = executionContext.getFormContext();
formContext.getControl("s_qd").addOnLoad(GetTotalResourceCount);
}
Any ideas how I can fix this? Is this a known issue with the new D365 wave 1 update?
Thanks!
This is the problem with unsupported (undocumented) code usage, which will break in future updates.
Unsupported:
var gridCtx = formContext._gridControl;
You have to switch to these supported methods.
function doSomething(executionContext) {
var formContext = executionContext.getFormContext(); // get the form Context
var gridContext = formContext.getControl("Contacts"); // get the grid context
// Perform operations on the subgrid
var grid = gridContext.getGrid();
}
References:
Client API grid context
Grid (Client API reference)

class inheritance in javascript/angular

I am working on my hello world project. I have two pages let's call them "configuration" and "add configuration" *.html. Each one has its own controller like this:
angular.module('MissionControlApp').controller('ConfigController', ConfigController);
angular.module('MissionControlApp').controller('AddConfigController', AddConfigController);
Now, each controller has some properties that very much overlap:
function ConfigController($routeParams, ConfigFactory, $window){
var vm = this;
vm.status;
vm.projectId = $routeParams.projectId;
vm.selectedProject;
vm.configurations;
vm.selectedConfig;
vm.selectedRecords;
vm.filteredConfig;
vm.newFile;
vm.fileWarningMsg = '';
vm.addFile = function(){
var filePath = vm.newFile;
var encodedUri = encodeURIComponent(filePath);
vm.fileWarningMsg='';
ConfigFactory
.getByEncodedUri(encodedUri).then(function(response){
var configFound = response.data;
var configNames = '';
var configMatched = false;
if(response.status === 200 && configFound.length > 0){
//find an exact match from text search result
for(var i = 0; i < configFound.length; i++) {
var config = configFound[i];
for(var j=0; j<config.files.length; j++){
var file = config.files[j];
if(file.centralPath.toLowerCase() === filePath.toLowerCase()){
configMatched = true;
configNames += ' [' + config.name + '] ';
break;
}
}
}
}
if(configMatched){
vm.fileWarningMsg = 'Warning! File already exists in other configurations.\n' + configNames;
} else if(filePath.length > 0 && filePath.includes('.rvt')){
var file1 = { centralPath: filePath };
vm.selectedConfig.files.push(file1);
vm.newFile = '';
} else{
vm.fileWarningMsg = 'Warning! Please enter a valid file.';
}
}, function(error){
vm.status = 'Unable to get configuration data: ' + error.message;
});
};
My AddConfigController also wants to have the same functionality for addFile() so I just copy pasted the same code, but coming from C# i am sure i can do some class inheritance here, and just inherit from ConfigController and extend...right?
If this is super noob question. then apologies. js is a bit of a mystery to me.
function AddConfigController($routeParams, ConfigFactory, $window){
var vm = this;
vm.status;
vm.projectId = $routeParams.projectId;
vm.selectedProject = {};
vm.newConfig = {};
vm.newFile;
vm.fileWarningMsg = '';
vm.addFile = function(){
var filePath = vm.newFile;
var encodedUri = encodeURIComponent(filePath);
vm.fileWarningMsg='';
ConfigFactory
.getByEncodedUri(encodedUri).then(function(response){
var configFound = response.data;
var configNames = '';
var configMatched = false;
if(response.status === 200 && configFound.length > 0){
//find an exact match from text search result
for(var i = 0; i < configFound.length; i++) {
var config = configFound[i];
for(var j=0; j<config.files.length; j++){
var file = config.files[j];
if(file.centralPath.toLowerCase() === filePath.toLowerCase()){
configMatched = true;
configNames += ' [' + config.name + '] ';
break;
}
}
}
}
if(configMatched){
vm.fileWarningMsg = 'Warning! File already exists in other configurations.\n' + configNames;
} else if(filePath.length > 0 && filePath.includes('.rvt')){
var file1 = { centralPath: filePath };
vm.selectedConfig.files.push(file1);
vm.newFile = '';
} else{
vm.fileWarningMsg = 'Warning! Please enter a valid file.';
}
}, function(error){
vm.status = 'Unable to get configuration data: ' + error.message;
});
};
Since you asked about inheritance and you appear to be using ECMAScript 5, let me suggest taking a look at Object.create(). Specifically, the classical inheritance example.
That said, in AngularJS, a better solution would be to create a Service that manages files or configurations and put the addFile function in there. That way, both controllers could inject the service and call the same function when it is time to add a file. Likewise, other services and controllers that may need access to this functionality could inject it as well.

Can't get list filled from a promise and use it in html - aurelia

I can't get the finalList filled to use in my html file, it wil run the code to fill it before the promise all code. I need to use this array in my html document so it has to be a this.variable I am using Aurelia.
activate() {
var repoList = [];
var repos = this.http.fetch({Link to github api})
.then(response => response.json())
.then(repos => this.repos = repos);
var trello = new Trello;
trello.getBoards().then(boardList => this.boards = boardList);
var boards = trello.getBoards();
//add github repo to the associated trello board (works)
Promise.all([boards, repos]).then(function(values) {
var count = 0;
for (var i in values[0]) {
for (var a in values[1]) {
if (values[1][a].hasOwnProperty("name")) {
var repo = values[1][a].name.toLowerCase();
var board = values[0][i]['name'].toLowerCase();
repoList[count] = repo;
count++;
if (repo == board) {
console.log(repo + " " + board)
}
}
}
}
});
//this list is always empty (The problem)
this.finalList = repoList;
this.title = "Trello Boards";
}
Something like this should do it. Hard to decipher what's going on in the for loops.
activate() {
let reposPromise = this.http.fetch({Link to github api})
.then(response => response.json());
let boardsPromise = new Trello().getBoards();
return Promise.all([boardsPromise, reposPromise])
.then(([boards, repos]) => {
this.boards = boards;
this.repos = repos;
this.finalList = [];
for (var i in boards) {
for (var a in repos) {
if (values[1][a].hasOwnProperty("name")) {
var repo = values[1][a].name.toLowerCase();
var board = values[0][i]['name'].toLowerCase();
this.finalList.push(repo);
if (repo == board)
{
console.log(repo + " " + board)
}
}
}
}
});
this.title = "Trello Boards";
}
I believe Your finalList should be set inside the promise handler. Like this.
activate() {
var repoList = [];
//I always use this, and I am not sure what do you mean
//by this.finalList, but still I assume you know what you are doing
//And hence I use this!
var that = this;
var repos = this.http.fetch({Link to github api})
.then(response => response.json())
.then(repos => this.repos = repos);
var trello = new Trello;
trello.getBoards().then(boardList => this.boards = boardList);
var boards = trello.getBoards();
//add github repo to the associated trello board (works)
Promise.all([boards, repos]).then(function(values) {
var count = 0;
for (var i in values[0]) {
for (var a in values[1]) {
if (values[1][a].hasOwnProperty("name"))
{
var repo = values[1][a].name.toLowerCase();
var board = values[0][i]['name'].toLowerCase();
repoList[count] = repo;
count++;
if (repo == board)
{
console.log(repo + " " + board)
};
}
};
};
//I believe when promise resolves. You should set the repoList.
that.finalList = repoList;
that.title = "Trello Boards";
});
}
My question is, do you really wanna set title and finalList to this? Just asking.
Hope this helps!

How to return array from JavaScript function that retrieves data from text file?

I am building a Windows 8 Store app with HTML/CSS/JavaScript. I am reading in data from a text file through a function, and then putting that data into an array. I am trying to return the array through the function, but it is not working. Any help would be greatly appreciated. I've attached my code snippet.
// Load user data
var DefineUserData = function LoadUserData() {
return Windows.Storage.ApplicationData.current.localFolder.getFileAsync(loadfile).done(function (UserFile) {
return Windows.Storage.FileIO.readTextAsync(UserFile).done(function (fileResult) {
var userdata = new Object();
var dataobject = {};
var innercount;
var outercount;
var fileResultByLines = fileResult.split("\n");
for (outercount = 0; outercount <= (fileResultByLines.length - 2) ; outercount++) {
var tempArray = fileResultByLines[outercount].split(",");
dataobject.metrictitle = tempArray[0];
dataobject.numinputs = tempArray[1];
dataobject.inputs = new Array();
for (innercount = 0; innercount <= parseInt(dataobject.numinputs) ; innercount++) {
dataobject.inputs[innercount] = tempArray[innercount + 2];
}
userdata[outercount] = dataobject;
}
return userdata;
});
},
function (errorResult) {
document.getElementById("resbutton1").innerText = errorResult;
})
}
Your DefineUserData function is returning a Promise, not a value. Additionally done functions don't return anything. Instead you'll need to use then functions instead of done functions in DefineUserData and then handle add a done function (or then) to the code that calls this function.
Also, You can make your promises easier to read, and easier to work with by chaining then functions instead of nesting them.
Currently on Win7 at the office so I can't test this, but try something similar to this pseudo-code. Note then functions instead of done. The last then returns your data. Sample snippet afterwards to illustrate calling this and handling the result.
// modified version of yours
var DefineUserData = function LoadUserData() {
return Windows.Storage.ApplicationData.current.localFolder
.getFileAsync(loadfile)
.then(function (UserFile) {
return Windows.Storage.FileIO.readTextAsync(UserFile);
}).then(function (fileResult) {
var userdata = new Object();
var dataobject = {};
var innercount;
var outercount;
var fileResultByLines = fileResult.split("\n");
for (outercount = 0; outercount <= (fileResultByLines.length - 2) ; outercount++) {
var tempArray = fileResultByLines[outercount].split(",");
dataobject.metrictitle = tempArray[0];
dataobject.numinputs = tempArray[1];
dataobject.inputs = new Array();
for (innercount = 0; innercount <= parseInt(dataobject.numinputs) ; innercount++) {
dataobject.inputs[innercount] = tempArray[innercount + 2];
}
userdata[outercount] = dataobject;
}
return userdata;
},
function (errorResult) {
document.getElementById("resbutton1").innerText = errorResult;
});
}
// some other code...
DefineUserData.done(function (userdata) {
// do something
});

Categories

Resources