I wonder if anyone can see a problem with this for loop.
I'm using parse, the for loop is inside a success callback for an object query.
When the loop runs, i jumps to response.length before it even finishes it's first loop
var e = [];
for (i = 0; i < response.length; i++) {
console.log("length: " + response.length);
var query = new Parse.Query(conEvent.Events);
query.get(response[i].get("eventID"), {
success: function (result) {
var object = result;
console.log("i: " + i)
e[i] = {
"name": object.get("name"),
"description": object.get("description"),
"dates": conEvent.datesToArray(object.get("dates")),
"ufDates": object.get("dates"),
"creator": object.get("creator"),
"id": object.id,
"invited": conEvent.getInvited(object.id)
}
console.log(e);
},
error: function (error) {
alert("Error: " + error.code + " " + error.message);
}
});
}
at the moment:
console.log("length: " + response.length); outputs "length: 2"
console.log("i: " + i) outputs "i: 2"
A more contextual view of the loop if anyone needs it:
this.getEvents = function () {
//get all the events user is invited to, list them and list the last....3? actions on the event
//display most likely date
//display number of users voted
//go green when date chosen
console.log("getEvents");
var Invite = Parse.Object.extend("Invite");
var query = new Parse.Query(Invite);
query.equalTo("username", Parse.User.current().get("username"));
query.find({
success: function (response) {
var e = [];
for (i = 0; i < response.length; i++) {
console.log("length: " + response.length);
var query = new Parse.Query(conEvent.Events);
query.get(response[i].get("eventID"), {
success: function (result) {
var object = result;
console.log("i: " + i)
e[i] = {
"name": object.get("name"),
"description": object.get("description"),
"dates": conEvent.datesToArray(object.get("dates")),
"ufDates": object.get("dates"),
"creator": object.get("creator"),
"id": object.id,
"invited": conEvent.getInvited(object.id)
}
console.log(e);
},
error: function (error) {
alert("Error: " + error.code + " " + error.message);
}
});
}
conEvent.myEvents = e;
console.log(e);
$scope.$apply();
}
});
}
Related
I created this function to obtain GitHub issues:
retrieveEnerpriseIssues: function(repoOrg, repoName, callback) {
let data = null;
// token auth
octokit.authenticate({
type: 'basic',
username: config.githubEnterprise.username,
password: config.githubEnterprise.token
});
async function paginate(method) {
let response = await method({
q: "repo:" + repoOrg + "/" + repoName + " is:issue",
per_page: 100
});
data = response.data.items;
var count = 0;
while (octokit.hasNextPage(response)) {
count++;
console.log(`request n°${count}`);
response = await octokit.getNextPage(response);
data = data.concat(response.data.items);
}
return data;
}
paginate(octokit.search.issues)
.then(data => {
callback(data);
})
.catch(error => {
console.log(error);
});
}
It is called in this function which takes the issues, filters out all of the unwanted keys into json format and puts it in my db.
extractToDb: function() {
let gitIssues = null;
for(var i = 0; i < config.githubEnterprise.orgs.length; i++) {
for(var j = 0; j < config.githubEnterprise.orgs[i].repos.length; j++) {
gitHubService.retrieveEnerpriseIssues(
config.githubEnterprise.orgs[i].owner,
config.githubEnterprise.orgs[i].repos[j].repoName,
function(data, err) {
if(err) {
console.log('err: ', err);
} else {
gitIssues = data;
}
gitIssues = JSON.stringify(gitIssues);
gitIssues = JSON.parse(gitIssues);
let issueFormatForDb = null;
for(var i = 0; i < gitIssues.length; i++) {
issueFormatForDb = gitIssues[i];
const body = '{' +
'"github_id": "' + issueFormatForDb.id + '",' +
'"issue_title": "' + issueFormatForDb.title + '",' +
'"issue_number": "' + issueFormatForDb.number + '",' +
'"issue_url": "' + issueFormatForDb.url + '",' +
'"issue_state": "' + issueFormatForDb.state + '"' +
'}';
console.log('Body: ', body);
getGitHubIssues.postToDb(body);
}
});
}
}
}
I'd like to take this a step further by filtering out any issues where the state is closed. How is this done and should it be handled in my retrieveEnerpriseIssues function or my extractToDb?
Possible solution
I tried this in my extractToDb function:
gitIssues = JSON.parse(gitIssues);
gitIssues = _.where(gitIssues, {state: "open"});
let issueFormatForDb = null;
Is it the best solution or is there a better way?
As #givehug stated:
Better use _.filter, or native filter method like
gitIssues = gitIssues.filter(i => i.state === 'open')
I think .where was deprecated in later versions of lodash github.com/lodash/lodash/wiki/Deprecations. Other than that its perfectly fine.
I just realsied I can filter the state in my paginate function with this:
let response = await method({
q: "repo:" + repoOrg + "/" + repoName + " is:issue" + " label:issue_label" + " state:open",
per_page: 100
});
I have few problems with below code.Can anyone help?
The if (currentStatus!="undefined") block in getStatusUsingAjax methid is not working.
unable to get the control out of getStatusUsingAjax method
$(document).ready(
loadStatus()
);
function loadStatus(x) {
$('.a-IRR-table tr').each(function(i) {
var val = $(this).find("td").eq(0).text();
link = $(this).find("td").eq(0).find("a").attr("href");
linkTag = $(this).find("td").eq(0).find("a");
`if ((val !== "-") && (val !== "")) {
console.log("val is" + val);
if (verifyrequestArray(val)) {
console.log("inside second if");
} else {
console.log("inside else");
sleep(1.5 * 1000);
var updatedStatus2 = getStatusUsingAjax(val, link);
console.log("UpdatedStatus2 is " + updatedStatus2);
setTooltip(linkTag, updatedStatus2);
}
}
});
}
function verifyrequestArray(id) {
var newArray = requestArray.toString().split('-');
console.log("NewArray is :" + newArray);
for (i = 0; i < newArray.length; i++) {
// I'm looking for the index i, when the condition is true
if (newArray[i] === id) {
console.log("request id found" + newArray[i]);
break;
} else {
console.log("request id not found" + newArray[i]);
return false;
}
}
}
function getStatusUsingAjax(requestValue, currentlink) {
console.log("patch req: " + requestValue);
console.log("Link is " + currentlink);
var currentStatus;
GM_xmlhttpRequest({
method: "GET",
url: currentlink,
onload: function(response) {
if ($(response.responseText).find("#P16_STATUS2").size() === 1) {
currentStatus = $(response.responseText).find("#P16_STATUS2").text();
console.log("Current Status from #P16_STATUS2 is :" + currentStatus);
console.log("Final URL is " + response.finalUrl);
}
}
});
// console.log("Final URL is " +response.finalUrl);
if (currentStatus != "undefined") {
var pusharr = [requestValue + "-" + currentStatus];
requestArray.push(pusharr);
console.log("Updated Array is " + requestArray);
return currentStatus;
}
}
function setTooltip(currentTag, status2) {
console.log("in settooltip" + currentTag);
currentTag.attr("title", status2); //setting status a tooltip
}
Any clue where the error is?
fn getStatusUsingAjax is async, you can not get return value using:
var updatedStatus2 = getStatusUsingAjax(val, link);
You sholud create callback:
function getStatusUsingAjax(val, link, callback){
//...
// do not use return currentStatus, call calback fn instead
callback(currentStatus)
}
and call it using:
getStatusUsingAjax(val, link, function(updatedStatus2){
console.log("UpdatedStatus2 is " + updatedStatus2);
setTooltip(linkTag, updatedStatus2);
});
I'm trying to retrieve images on Facebook Parse SDK, and I can't because of this error. And I don't know what i'm doing wrong because I use a conditional in order to no not to create a new variable if this is empty or undefined. This is the code (the console log points the error in the line where i'm creating the var ImageFl):
var Encharcamientos1 = Parse.Object.extend("Report");
var query = new Parse.Query(Inundaciones1);
query.equalTo("Tipo_Reporte", "Encharcamientos");
query.find({
success: function(results) {
// Do something with the returned Parse.Object values
for (var i = 0; i < results.length; i++) {
if (!object.get('ImageFile') || object.get('ImageFile') !== '' || typeof object.get('ImageFile') !== 'undefined') {
var imageFl = object.get('ImageFile');
var imageURL = imageFl.url();
$('.imagen')[0].src = imageURL;
}
var object = results[i];
L.marker([object.get('Latitud'),object.get('Longitud') ], {icon: EncharcamientosIcon}).bindPopup(' <p><span class="grande"> ' + object.get('Tipo_Reporte') + ' </span></p><p>Fecha: ' + object.get('Fecha') + ' </p><p>Hora: ' + object.get('Hora') + '<div class="imagen"></div>' + '</p><p>Comentarios:<br /> ' + noundefined(object.get('Comentario')) + '</p>').addTo(Encharcamientos).addTo(todos);
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
The object wasn't being set before the if statement. update, added code from comments
var Encharcamientos1 = Parse.Object.extend("Report");
var query = new Parse.Query(Inundaciones1);
query.equalTo("Tipo_Reporte", "Encharcamientos");
query.find({
success: function(results) {
// Do something with the returned Parse.Object values
for (var i = 0; i < results.length; i++) {
var object = results[i]; // <-- THIS NEEDS TO BE BEFORE IF STATEMENT
var imageFl = object.get('ImageFile');
alert(imageFl);
if (imageFl !== '' && typeof imageFl !== 'undefined') {
var imageURL = imageFl.url();
$('.imagen')[0].src = imageURL;
}
L.marker([object.get('Latitud'),object.get('Longitud') ], {icon: EncharcamientosIcon}).bindPopup(' <p><span class="grande"> ' + object.get('Tipo_Reporte') + ' </span></p><p>Fecha: ' + object.get('Fecha') + ' </p><p>Hora: ' + object.get('Hora') + '<div class="imagen"></div>' + '</p><p>Comentarios:<br /> ' + noundefined(object.get('Comentario')) + '</p>').addTo(Encharcamientos).addTo(todos);
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
I've usually been making queries to a class for a single, directed object using the objectId and it's all been working smoothly. However I am now trying to get all of the objects in a given class.
var values;
var Class = Parse.Object.extend(className);
var query = new Parse.Query(Class);
console.log(objectID);
if (typeof objectID !== "undefined") { //if the user specified objectID
query.get(objectID, {
success: function(retrieveObject) {
for (var i = 0; i < keys.length; i++) {
values[i] = query.get(keys[i]);
}
},
error: function(error) {
console.log("Failed to retrieve " + className + ': ' + error.message);
}
});
} else { //if not return all
query.limit(1000);
query.exists("objectId");
query.find({
success: function(results) {
console.log("the results are " + results);
for (var i = 0; i < results.length; i++) {
for (var j = 0; j < keys.length;j ++)
console.log("key " + j + " is " + keys[j]);
console.log("the result for " + j + " is " + results[i]);
var object = results[i];
values[i][j] = object.get(keys[j]);
console.log("the value for the key in result is " + values[i][j]);
}
},
error: function(error) {
console.log("Failed to retrieve " + className + ': ' + error.message);
}
});
}
For the life of me I cannot figure out why this does not work. "results" comes out as an array of the correct number of values, but each is "[object Object]"
Any ideas?
Is there an alternative to using .load to refresh the contents of a Div? Bascially I'm using .load below to reload the div after an object has been removed. But at the moment this is'nt working correctly.
.load is returning a div without results, even though there should be objects within it. When I refresh the page manually the correct results show.
Therefore, Could I just remove the object from view the user has clicked on instead?
/////////////////////SECTION 1 - This code block returns the current users friends to the page. THIS IS NOT USED IN THE FILTER//////
$('#containerFriends').empty();
$('#friendsProfile').hide();
$('#container').empty();
$('#containerFriendsConnected').empty();
var currentUser = Parse.User.current();
var FriendRequest = Parse.Object.extend("FriendRequest");
var queryOne = new Parse.Query(FriendRequest);
queryOne.equalTo("toUser", currentUser);
var queryTwo = new Parse.Query(FriendRequest);
queryTwo.equalTo("fromUser", currentUser);
var mainQuery = Parse.Query.or(queryOne, queryTwo);
mainQuery.include('toUser');
mainQuery.include('fromUser');
mainQuery.equalTo("status", "Connected");
mainQuery.find({
success: function(results) {
var friends = [];
for (var i = 0; i < results.length; i++) {
friends.push({
imageURL: results[i].get('toUser').get('pic'),
username: results[i].get('toUser').get('username'),
userId: results[i].get('toUser').id,
status: results[i].get('status'),
// Saves the object so that it can be used below to change the status//
fetchedObject: results[i]
});
}
var select = document.getElementById("FriendsConnected");
$.each(friends, function(i, v) {
var opt = v.username;
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
})
$('#containerFriends').empty();
$('#containerFriendsConnected').empty();
_.each(friends, function(item) {
var wrapper = $('<div class="portfolio-item-thumb one-third"></div>');
wrapper.append('<img class="responsive-image friendImgOutline" src="' + item.imageURL + '" />' + '<br>');
wrapper.append('<div class="tag">' + item.username + '</div>');
wrapper.append('<div type="button" class="btn btn-danger mrs decline">' + 'Unfriend' + '</div>');
$('#containerFriends').append(wrapper);
//The following lets the user accept or decline a friend request by changing the status the status from Pending to Declined/////
wrapper.children('.decline').click(function() {
$(".decline").click(function() {
item.fetchedObject.set("status", "Rejected");
$( "#containerFriends" ).load("friends.html #containerFriends" );
item.fetchedObject.save(null, {
success: function(results) {
console.log("REJECTED");
},
error: function(contact, error) {
// The save failed.
// error is a Parse.Error with an error code and description.
alert("Error: " + error.code + " " + error.message);
}
});
});
});
});
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});