Mocktheduck Mocktheduck - 1 month ago 5x
JSON Question

Trying to remake an array of JSON but it returns the same first element

I'm trying to parse a list of JSONs and remake the JSON and add it to a different list. The problem is, one of the fields I need gets its value from a promise so I'm doing the processing inside that promise function.

for the list [a, b ,c], in my promise, I always have the first element for some reason. Any idea why?

for (var i = 0; i < self.pendingInterviews.length; i++) {
self.interviewModel = {
interviewId: self.pendingInterviews[i].id,
status: self.pendingInterviews[i].status,
location: self.pendingInterviews[i].location,
start: self.pendingInterviews[i].start,
hideCheck: null
var promise = checkParticipant(self.pendingInterviews[i].id);
function(result) {
self.interviewModel.hideCheck = result;
function(errResponse) {
console.error('Error while check part');

My object literal:

this.interviewModel = {
interviewId: null,
status: null,
location: null,
start: null,
hideCheck: null

Example of it being populated (JSON):


What self.checkedInterviews has in the end (JSON):


The same thing 7 times...

I figured this is happening because javascript is Async and the promise function only gets the last thing. How do I fix it?


The problem is that by the time your promise .then functions run, the for loop is already finished, and self.interViewmodel already has the value of the last value of i.

So don't use self.interviewModel in them.

To make sure the promise doesn't "see" the new version of the variable, add another layer of function around it to invoke it, passing in the version it should use:

    (function(interviewModel) {
        return function(result) {
            interviewModel.hideCheck = result;
    function(errResponse) {
      console.error('Error while check part');