【问题标题】:jquery multiple http get requests with promisejquery 多个带有承诺的 http get 请求
【发布时间】:2020-05-19 01:03:14
【问题描述】:


我正在尝试使用 jquery get 从服务器获取多个图像。

 $.each(result.Data.Files, function (i, v) {

        $.get('/mobile/image?path=' + v, function (res) {

            if (res.Success) {
                $('#images-container').append(`<img alt="Image Title" src="${res.Image}">`);
            }
        });

    });

添加所有图像后,我想调用一个 jquery 插件来处理这些图像。
我如何使用 promise 来做到这一点?
我尝试了类似的东西:

     $.when(
            $.each(result.Data.Files, function (i, v) {
                $.get('/mobile/image?path=' + v);
            })
        ).then(function () {

            $("#images-container").image_plugin();

            for (var i = 0; i < arguments.length; i++) {

                let src = arguments[i];
                console.log(src)
            }



        });

但我在 then 部分得到的只是网址,而不是实际的 base64 响应
谢谢

【问题讨论】:

  • $.each() 不返回任何内容。所以你的$.when() 没有任何作用。改用 map() 并返回由 $.get 创建的承诺

标签: javascript jquery promise


【解决方案1】:

使用Deferred

var defs = [];

//create Deferred for each item in array and push to defs array
$.each(result.Data.Files, function () {
    defs.push($.Deferred());
});

$.when.apply($, defs).then( function(v){
    //runs when all deferred are resolved
    $("#images-container").image_plugin(); 
    console.log(v)
});

$.each(result.Data.Files, function (i, v) {
     $.get('/mobile/image?path=' + v, function (res) {
        if (res.Success) {
            $('#images-container').append(`<img alt="Image Title" src="${res.Image}">`);
            defs[i].resolve(res.Image);
            //resolve i'th deferred
        }
    });
});

【讨论】:

  • defs[]=$.Deferred();此行引发异常。你是什​​么意思?
  • 哎呀..今天的php太多了..修复了它
猜你喜欢
  • 2014-05-30
  • 2012-12-25
  • 2019-09-17
  • 2015-11-26
  • 2019-06-08
  • 1970-01-01
  • 2017-12-08
  • 2013-12-02
  • 2017-05-08
相关资源
最近更新 更多