我已经更新了你的
fiddle
.
你的原因
titles
正在更新,因为
作为参数传递的数组和数组引用了相同的对象。我不是推同一个对象,而是创建新对象,
items.push({...config})
const titles = [
{ title: 'avatar' },
{ title: 'jurassic' },
{ title: 'black panther' }
];
transformData(titles.slice(0), items => {
const problem = items.length !== titles.length;
const debugg ={
problem: problem,
counts: {
items: items.length, // echos 2
titles: titles.length // echos 3
},
items: items, // echos an object with 3 arrays inspector shows length:3
titles: titles // echos an object with 3 arrays inspector shows length:3
};
console.log('debugg', debugg)
$('pre').text(JSON.stringify(debugg, null, 2))
});
function transformData(configs, next) {
const self = this;
const items = [];
const last = configs.length;
const p = []
$.each(configs, function(i, config){
items.push({...config})
p.push($.ajax({
url: 'https://www.omdbapi.com/?apikey=f4e09aec&&t=' + items[i].title,
type: 'GET',
crossDomain: true,
dataType: 'jsonp'
}))
})
Promise.all(p).then((values)=>{
for(var i =0;i<values.length;i++){
items[i].year = values[i].Year
}
next(items)
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre></pre>