简体   繁体   中英

jquery multiple http get requests with promise


I'm trying to get multiple images from server using 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}">`);
            }
        });

    });

After i append all images i want to call a jquery plugin to handle these images.
How can i do that using promise?
i tries something like:

     $.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)
            }



        });

but what i'm getting in the then section is just the urls and not the actual base64 response
thanks

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM