尝试重新制作一个JSON数组,但它返回相同的第一个元素

时间:2016-09-16 11:01:39

标签: javascript json promise

我试图解析JSON列表并重新制作JSON并将其添加到其他列表中。问题是,我需要的一个字段从一个promise获得它的值,所以我在promise函数中进行处理。

对于列表[a,b,c],在我的承诺中,由于某种原因,我总是有第一个元素。知道为什么吗?

self.checkedInterviews=[];
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);
  promise.then(
    function(result) {
      self.interviewModel.hideCheck = result;
      self.checkedInterviews.push(JSON.stringify(self.interviewModel));
    },
    function(errResponse) {
      console.error('Error while check part');
    }
  );
}

我的对象文字:

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

正在填充的示例(JSON):

{"interviewId":10437,"status":"pending","location":"sdsa","start":-2179273464000,"hideCheck":false}

self.checkedInterviews到底有什么(JSON):

{"interviewId":10437,"status":"pending","location":"sdsa","start":-2179273464000,"hideCheck":false},{"interviewId":10437,"status":"pending","location":"sdsa","start":-2179273464000,"hideCheck":true},{"interviewId":10437,"status":"pending","location":"sdsa","start":-2179273464000,"hideCheck":false},{"interviewId":10437,"status":"pending","location":"sdsa","start":-2179273464000,"hideCheck":false},{"interviewId":10437,"status":"pending","location":"sdsa","start":-2179273464000,"hideCheck":true},{"interviewId":10437,"status":"pending","location":"sdsa","start":-2179273464000,"hideCheck":false}

同样的事情7次......

我认为这种情况正在发生,因为javascript是Async,而promise函数只能得到最后一件事。我该如何解决?

2 个答案:

答案 0 :(得分:1)

问题在于,当您的承诺.then函数运行时,for循环已经完成,self.interViewmodel已经具有i的最后一个值的值。

所以不要在其中使用self.interviewModel

确保承诺没有&#34;见&#34;新版本的变量,在它周围添加另一层函数来调用它,传入它应该使用的版本:

promise.then(
    (function(interviewModel) {
        return function(result) {
            interviewModel.hideCheck = result;
            self.checkedInterviews.push(JSON.stringify(interviewModel));
        }
    })(interviewModel),
    function(errResponse) {
      console.error('Error while check part');
    }
);

答案 1 :(得分:0)

在承诺完成后启动对象

执行以下操作

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