等待$ .each的异步功能,然后继续

时间:2018-08-21 14:34:24

标签: javascript jquery

我为this fiddle to help debug编写了以下代码...

如果您去找小提琴并继续按“ run”(运行)-您会注意到每次的结果都是不同的(它们应该是相同的)。我正在尝试完成两件事

  1. 我如何确保每次都year上的items[]键/ val处于打开状态–现在不一致。

  2. 我不想在titles期间更改transformData()。现在,数组正在被修改...我的尝试是transformData(titles.slice(0), items => {,但仍在更改。

    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;
        $.each(configs, function(i, config) {
            items.push(config);
            $.ajax({
                url: 'https://www.omdbapi.com/?apikey=f4e09aec&&t=' + items[i].title,
                type: 'GET',
                crossDomain: true,
                dataType: 'jsonp',
                success: function(results) {
                    if (results.Response != 'False') {
                        console.log(results);
                        items[i].year = results.Year;
                        if (i+1 === last) { next(items); }
                    }
                }
            });
        });
    }
    

1 个答案:

答案 0 :(得分:3)

我已经更新了您的fiddle。 您的titles之所以更新,是因为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>