object keys are undefined in if conditional, but inside the if statement I can access it - json

As the title states, I have a variable which is a javascript object, i'm comparing it with another js object by stringifying them. The problem is that the variable is completely accessible without calling the keys, so these
if(JSON.stringify(response) == JSON.stringify(lastcmd))
if(JSON.stringify(response.id) == JSON.stringify(lastcmd))
work perfectly fine, but accessing lastcmd's id key will cause it to throw undefined.
if(JSON.stringify(response) == JSON.stringify(lastcmd.id))
full code link here
Edit: Here's the JSON
{ "id" : "001", "app": "msgbox", "contents": { "title": "Newpaste", "message": "I'm a edited paste!" } }
Edit2: Here's the code on the post
const { BrowserWindow, app, dialog, ClientRequest } = require("electron");
const axios = require("axios");
const url = require("url");
let win = null;
let lastcmd;
function grabCurrentInstructions(fetchurl) {
return axios
.get(fetchurl)
.then(response => {
// handle success
//console.log(response.data);
return response.data;
})
.catch(function(error) {
// handle error
console.log(error);
});
}
function boot() {
//console.log(process.type);
win = new BrowserWindow({
resizable: true,
show: false,
frame: false
});
win.loadURL(`file://${__dirname}/index.html`);
//Loop everything in here every 10 seconds
var requestLoop = setInterval(getLoop, 4000);
function getLoop() {
grabCurrentInstructions("https://pastebin.com/raw/i9cYsAt1").then(
response => {
//console.log(typeof lastcmd);
//console.log(typeof response);
if (JSON.stringify(response.app) == JSON.stringify(lastcmd.app)) {
console.log(lastcmd.app);
clearInterval(requestLoop);
requestLoop = setInterval(getLoop, 4000);
} else {
lastcmd = response;
switch (response.app) {
case "msgbox":
dialog.showMessageBox(response.contents);
//console.log(lastcmd);
clearInterval(requestLoop);
requestLoop = setInterval(getLoop, 1000);
}
}
}
);
}
}
app.on("ready", boot);
And here's the error:
(node:7036) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'id' of undefined
at grabCurrentInstructions.then.response (C:\Users\The Meme Machine\Desktop\nodejsprojects\electronrat\index.js:42:64)
at process._tickCallback (internal/process/next_tick.js:68:7)

Thanks to user str I saw that my lastcmd was undefined when I ran the comparison the first time, this would break it and thereby loop the same error over and over, by addding
grabCurrentInstructions("https://pastebin.com/raw/i9cYsAt1").then(
response => {
lastcmd = response;
}
);
below this line
win.loadURL(`file://${__dirname}/index.html`);
I made sure that the last command sent while the app was offline wouldn't be executed on launch and fixing my problem at the same time!

Related

I wanted to get users from an array of names but it throws an error

Create an async function getUsers(names), that gets an array of GitHub logins, fetches the users from GitHub and returns an array of GitHub users.
The GitHub url with user information for the given USERNAME is: https://api.github.com/users/USERNAME.
There’s a test example in the sandbox.
Important details:
1.There should be one fetch request per user.
2.Requests shouldn’t wait for each other. So that the data arrives as soon as possible.
3.If any request fails, or if there’s no such user, the function should return null in the resulting array.
Input:array;
output:array;
TypeError: r.json is not a function
async function getUsers(names) {
let requests = names.map(name => fetch(`https://api.github.com/users/${name}`));//gets users
let users = [];//Final answer
await Promise.allSettled(requests)
.then(responses => new Promise(function(resolve) {// returrn correct users promise
let corrects = [];
responses.forEach((result) => {
if (result.value.ok) { //check statuse 200-299
corrects.push(result);
} else {
users.push(result); // else add to Finell answer null
}
})
resolve(corrects); //return users with 200-299 statuse
}))
.then(corrects => Promise.all(corrects.map(r => r.json()))) //processing
.then(results => results.forEach(result => users.push(result))); //add to finel answer correct requests
return users;
}
//Input:array;
//output:array;
//TypeError: r.json is not a function
There's a number of things slightly wrong with your code, but I think the main issue is that you're pushing the results of allSettled into 'corrects' but, you want to push the .value instead.
You also don't actually do anything with corrects and only return failed requests.
But here's a version that cleans it all up. I'm assuming you want to ignore failed requests, but not sure, because it's hard to tell from your code:
async function getUsers(names) {
const requests = names.map(name => fetch(`https://api.github.com/users/${name}`));//gets users
const results = await Promise.allSettled(requests);
const successResponses = results
.filter(result => {
// Filter out rejected promises and error responses.
// I think this is what you want but not sure?
if (result.status!=='fulfilled' || !result.value.ok) return false;
});
return Promise.all(successResponses.map(response => response.json()));
}
Promise.allSettled is a very special-purpose function and you will not need it in most cases. There are other pain points like the explicit promise constructor anti-pattern. Instead decompose the problem into smaller, simple parts -
getUser(name) takes a single name and returns a user object or null
getUsers(names) takes a list of names and maps getUser over each
async function getUser(name) {
try {
const res = await fetch(`https://api.github.com/users/${name}`)
return res.ok ? res.json() : null
}
catch (err) {
return null
}
}
function getUsers(names) {
return Promise.all(names.map(getUser))
}
getUsers(["ivg", "glennsl", "jeffsco", "nosuchuser111"]).then(console.log, console.error)
.as-console-wrapper { min-height: 100%; top: 0; }
[
{
"login": "ivg",
"id": 2336698,
"node_id": "MDQ6VXNlcjIzMzY2OTg=",
...
},
{
"login": "glennsl",
"id": 5207036,
"node_id": "MDQ6VXNlcjUyMDcwMzY=",
...
},
{
"login": "jeffsco",
"id": 4043178,
"node_id": "MDQ6VXNlcjQwNDMxNzg=",
...
},
null // user not found
]

Uncaught SyntaxError: Unexpected number in kendo ui

I have kendo ui popup which sends a request to an action method. The action method returns json and then my code breaks in the kendo.all.min.js file and the error method says Uncaught SyntaxError: Unexpected number
My kendo code below:-
var cloudStore = new kendo.data.DataSource({
//batch: true,
pageSize: 25,
transport: {
create: {
url: "/Admin/AddCloudStore", //(/ControllerName/ActionName)
type: "POST"
},
update: {
url: "/Admin/UpdateCloudStore",
type: "POST"
},
parameterMap: function (data, operation) {
console.table(data);
var result = {};
// For update and create send the entire object
if (operation === "update" || operation === "create") {
return data;
//return JSON.stringify({ service: data });
}
return null;
}
},
schema: {
model: cloudStoreModel,
errors: "error"
},
error: function (e) {
console.log(e);
}
});
Am I suppose to return something else from the action? Any help on the issue would be appreciated
Edit: Okay seems like the problem is with what I am return from my .net action method. Adding my action method below:-
public ActionResult AddCloudStore(DataAccess.Model.domain_config_cloud store)
{
try
{
using (var context = new DataAccess.Model.CondadoMediaVault())
{
if (store.cld_cmp_key <= 0) store.cld_cmp_key = Session["sel_domain_key"].ConvertToLong();
var list = context.domain_config_cloud.Where(x => x.cld_cmp_key == store.cld_cmp_key && x.cld_is_active && x.cld_category == "primary").ToList();
if (list.Count > 0)
return Json("There is already a primary cloud store."); //returning string
long user_key = 0;
long.TryParse(Convert.ToString(Session["user"]), out user_key);
var maxKey = context.domain_config_cloud.OrderByDescending(x => x.cld_key).FirstOrDefault();
if (maxKey == null || maxKey.cld_key == 0)
return Json("Error"); //returning string
else
store.cld_key = maxKey.cld_key + 1;
context.domain_config_cloud.Add(store);
context.SaveChanges();
}
}
catch (Exception ex)
{
MediaVault.BLL.ErrorLoggging.DbExceptionLog.LogError(ex);
}
return Json(store); //returning object
}
So the kendo ui code breaks when a string is returned from the action method. If an object is returned the code does not break. What is the exact return type which is expected by kendo ui?

NSwag Angular 5 how to get the json response?

I'm accessing an api and I generated using NSwagStudio a type script version of the api calls to use as services. I get the response from the server and seems to work fine, but I don't know how to access the json file with the response. I tried subscribing to the method that I'm calling but I always get null as a response. Any help or guidelines will be appreciated it.
Here is an example of the code generated by NSwagStudio and my implementation to subscribe to the response.
apiSubmissionGetResultMessageGet(...) {
protected processApiSubmissionGetResultMessageGet(response: HttpResponseBase): Observable<void> {
const status = response.status;
const responseBlob =
response instanceof HttpResponse ? response.body :
(<any>response).error instanceof Blob ? (<any>response).error : undefined;
let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }};
if (status === 200) {
return blobToText(responseBlob).flatMap(_responseText => {
return Observable.of<void>(<any>null);
});
} else if (status !== 200 && status !== 204) {
return blobToText(responseBlob).flatMap(_responseText => {
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
});
}
return Observable.of<void>(<any>null);
}
}
And this is where I'm trying to subscribe:
getSubmissionDetails(string): void {
this.client.apiSubmissionGetSubmissionDocumentGet('documentId')
.subscribe(
data => {
this.submissionList = this.submissionList;
console.log('data: ', data);
},
(error: any) => this.errorMessage = <any> error);
}
The return type is Observable<void> which means that it doesnt return anything...
Check that the operation has a response type in the swagger spec and regenerate.

Chrome.storage.sync.get() seems to be duplicating keys?

I am saving some settings using the following sequence
var getSettings = async function() {
var settings;
try {
settings = await authenticatedGET(server_url + SETTINGS_ENDPOINT);
return settings;
} catch (error) {
console.log("Settings Fetch Failed: " + error);
throw new Error(error);
}
}
const setLocalSettings = function(settings) {
chrome.storage.sync.set({ 'LML_Settings': JSON.parse(settings) }, function() {
console.log("Settings saved locally");
});
}
At the line right after the setLocalSettings function definition, the 'settings' object logs out as
{"email_format":"individual","close_tab":true,"frequency":"DAILY"} (correctly as intended). When I go to fetch the settings using this sequence:
chrome.storage.sync.get('LML_Settings', function(LMLSettingsContainer) {
console.log(LMLSettingsContainer);
if (LMLSettingsContainer.LML_settings.close_tab == "true") {
closeCurrentTab();
}
})
LMLSettingsContainer logs out as
{
"LML_Settings": {
"close_tab": true,
"email_format": "individual",
"frequency": "DAILY"
}
}
accessing my settings with LMLSettingsContainer.LML_Settings["<setting>"] is a bit annoying (and its the whole reason I named the top variable LMLSettingsContainer).
Does anyone know if there's a way to have chrome save/get these values unwrapped?
chrome.storage.sync.get('LML_Settings', ({LML_settings}) => { ... }) works, per #wOxxOm

cannot read property 'length' of undefined in angular

I have an json array and i am trying to get the length of that array but i am getting an error of undefined.
$http.post('http://localhost:8099/mescc/seci/tools/ManageSettings',addOrUpdateJson)
.success(
function(dat, status,
headers, config) {
$scope.loading=false;
$scope.table=true;
$scope.allConfigDatabase = dat;
for (var i = 0, len = dat.data.length; i < len; i++)
{
$scope.editingData[$scope.allConfigDatabase.data[i].id] = false;
}
$scope.searchParameter = "";
$scope.updateView=false;
$scope.$apply();
})
.error(
function(data, status,headers, config) {
});
The response of the POST request is in your 'dat' parameter of the success function. I'm pointing that just because I see a you use 'data' for the error function, maybe a previous rename had caused the error.
This 'undefined' error, means that your json response doesn't have a 'data' property. To be clearer, it doesn't look like:
{ foo: {}, bar: {}, data:[1,2,3,4] }
You can use the utility function provided by angular to better check on the client side:
if (angular.isArray(dat.data)) {
//...
}