This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 12 months ago.
function addIDS() {
const imdbIDs = [];
imdbIDs.push("id1");
imdbIDs.push("id2");
...
return imdbIDs ;
}
function getThemoviedbIDs(IDs) {
let arr = [];
let urls = [];
for(let i = 0; i < IDs.length; i++) {
urls.push(`...${imdb_ids[i]}...`);
}
$.each(urls, (i, u) => {
$(function() {
$.ajax({
url: u,
dataType: 'json',
success: function(data) {
arr.push(data.tv_results[0].id);
},
statusCode: {
404: function() {
alert('Err');
}
}
});
});
});
return arr;
}
function getDetails(themoviedbID) {
console.log(themoviedbID);
console.log(`...${themoviedbID[0]}`);
}
const imdbIDs = addIDS();
console.log("IMDB IDs: ", imdbIDs);
const themoviedbIDs = getThemoviedbIDs(imdbIDs);
console.log("themoviedbIDs: ", themoviedbIDs);
const themoviedbIDs = getThemoviedbIDs(themoviedbIDs);
console.log("themoviedbIDs: ", themoviedbIDs);
I am using themoviedb database.
populate() I add imdb IDs to the imdbIDs array, then I get themoviedb IDs by getThemoviedbIDs() function.
In the getDetails() function I would like to make ajax request just like in the getThemoviedbIDs() function, but unfortunatelly there is a problem in there. console.log(themoviedbID) output the appropriate array, but console.log(...${themoviedbID[0]}) output .../undefined...
I can get enough information about the series if I am using themoviedb ID.
Related
This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 1 year ago.
Any idea why the following return an empty array? I cannot understand or debug this error. Initially, storearray1 returns array with values in it. Subsequent usage, storearray1 returns an empty array. If possible can help provide a solution to this problem. I am confused.
function f1(){
var storearray1=[];
for (var skip = 0; skip < 9000; skip = skip + 500) {
$.ajax({
url: "/api/routes?$skip=" + skip,
success: function(results) {
//Set result to a variable for writing
var objs = JSON.stringify(results);
var routetimeobjs = JSON.parse(objs);
storearray1.push(routetimeobjs['value']);
}
});
}
}
function showresult(){
console.log(storearray1);//work (refer to image)
var actualarray=storearray1;
console.log(actualarray); //does not work- return empty array
}
showresult();
Console Log for storearray1:
Try this.
var storearray1=[];
var calls = [];
for (var skip = 0; skip < 9000; skip = skip + 500) {
(function(skp) {
var c = $.ajax({
url: "/api/routes?$skip=" + skp,
success: function(results) {
//Set result to a variable for writing
var objs = JSON.stringify(results);
var routetimeobjs = JSON.parse(objs);
storearray1.push(routetimeobjs['value']);
}
});
calls.push(c);
})(skip);
}
$.when(...calls).then(() => console.log(storearray1));
This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I'm trying to generate an array from ajax result. When my code runs it populates the list. But once the ajax call is done, and I start iteration of that populated list, it doesn't output anything.
When I put it in debugging mode I can see that the array "tlitems" is getting populated.
But then after last item is added, it goes out.
var tlitems = [];
function GetTL() {
$.ajax({
type: 'GET',
url: '/PTL',
datatype: 'json',
headers: headers
}).done(function(ptl) {
$.each(ptl, function(key, value) {
var pid = this.pid;
var owner = this.strowner;
var dbtstamp = this.db_tstamp;
var tlt = "pi";
item = {}
item["_pid"] = personid;
item["_owner"] = owner;
item["_dbtstamp"] = dbtstamp;
item["_tlt"] = tlt;
tlitems.push(item);
});
}).fail();
$.each(tlitems, function(k, v) {
alert("Key: " + k + ", Value: " + v);
})
};
It should alert with K:V. But it just comes out.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
Please have a look at this method. In this function response I am calling two functions findConnectedUsersRelationship() and displayUsers(response.users).
The problem is displayUsers(response.users) method runs and gets result before findConnectedUsersRelationship(). My requirement is I need to run first findConnectedUsersRelationship() and second displayUsers(response.users). Second method depends on first method.
function filterUsers(location, gender, youngAge, oldAge, interests){
var userId = signedUserId;
$.post(urlHolder.filter, {
userId: userId,
location: location,
gender: gender,
youngAge: youngAge,
oldAge: oldAge,
interests: interests
}, function(response) {
console.log('User response <<>>', response.users.length);
var filteredUsers;
findConnectedUsersRelationship();
displayUsers(response.users);
});
}
// To find connected user relationship
var relationshipList = new Array;
function findConnectedUsersRelationship() {
try {
$.post(urlHolder.findConnectedUsersRelationship, {
userId : signedUserId
}, function(response) {
//console.log('response downforanything: ', JSON.stringify(response));
if (response) {
for (var counter = 0; counter < response.users.length; counter++) {
relationshipList.push(response.users[counter].id);
}
} else {
console.log('No connected users >>>> ');
}
//console.log('relationshipList.length',relationshipList);
console.log('relationshipList length in auto complete *** ',relationshipList.length);
});
} catch (e) {
console.log('findConnectedUsersRelationship Exception >>>', e);
}
}
$.post returns a promise.
You can use this to continue your code:
function filterUsers(location, gender, youngAge, oldAge, interests){
$.post(url, { ... }, function(response) {
findConnectedUsersRelationship().done(function() {
displayUsers(response.users);
});
});
}
and change your findConnectedUsersRelationship() to return the promise from its ajax function,so instead of:
function findConnectedUsersRelationship() {
$.post(...
it becomes
function findConnectedUsersRelationship() {
return $.post(...
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 7 years ago.
Im trying to make a simple comment system using React. I'm saving the comments in Parse. The problem is, when I retrieve the comments from Parse, I need to update the state of my component, but when I try to do it, I get an error "Uncaught ReferenceError: this.setState is not defined".
Not working code
loadComments() {
let Comment = Parse.Object.extend("Comment");
let query = new Parse.Query(Comment);
query.limit(15).find({
success: function(result) {
let data = [];
for (var i = 0; i < result.length; i++) {
var object = result[i];
data.push(object.toJSON());
}
this.setState({ data: data });
}
});
}
If I change my code it works, but I think that should have a better approach to this.
Working code
loadComments() {
let Comment = Parse.Object.extend("Comment");
let query = new Parse.Query(Comment);
let _this = this;
query.limit(15).find({
success: function(result) {
let data = [];
for (var i = 0; i < result.length; i++) {
var object = result[i];
data.push(object.toJSON());
}
_this.setState({ data: data });
}
});
}
You have two other options:
Function.prototype.bind:
success: function (result) {
// etc
}.bind(this)
An arrow function (requires es6), which uses the this from the surrounding scope:
success: (result) => {
// etc
}
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
function getEvents(userid,year,week) {
var items = [];
var path = "js/test.json";
$.getJSON( path).done(function( data ) {
items = data.sessions;
});
return items;
}
var list = getEvents(10,1991,13);
Here is my javascriot and I need to get an array to return from getEvents() method.
You should put the return statement inside the .done function as following:
function getEvents(userid,year,week) {
var items = [];
var path = "js/test.json";
$.getJSON( path).done(function( data ) {
items = data.sessions;
return items;
});
}