gpt4 book ai didi

javascript - 尝试重新创建 JSON 数组,但它返回相同的第一个元素

转载 作者:行者123 更新时间:2023-11-27 22:31:33 24 4
gpt4 key购买 nike

我正在尝试解析 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 是异步的,而 Promise 函数只获取最后一件事。我该如何修复它?

最佳答案

问题是,当您的 Promise .then 函数运行时,for 循环已经完成,并且 self.interViewmodel 已经具有最后一个值的值i

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

为了确保 Promise 不会“看到”变量的新版本,请在它周围添加另一层函数来调用它,并传入它应该使用的版本:

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');
}
);

关于javascript - 尝试重新创建 JSON 数组,但它返回相同的第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39529875/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com