Waiting for promise in for loop

后端 未结 2 389
感情败类
感情败类 2020-12-22 11:35

I have a bit of trouble getting into this whole async stuff. I\'m using pdf.js to read the contents of a pdf file. Everything is working, however the execution order is caus

2条回答
  •  旧巷少年郎
    2020-12-22 12:34

    Try using promises:

    function getText(data) {
        var contents = [];
        var promises = [];
    
        PDFJS.getDocument(data).then(function(pdf) {
            var numPages = pdf.pdfInfo.numPages;
    
            for (var i = 1; i <= numPages; i++) {
                var deferred = $.Deferred(); //Create a deferred object
                promises.push(deferred.promise()); //push promise to the list
    
                pdf.getPage(i).then(function(page) {
                    page.getTextContent().then(function(content) {
                        contents.concat(content.bidiTexts);
                        deferred.resolve(); //resolve the deferred object
                    })
                });
            }
    
            $.when.apply($,promises).then(function(){ //callback executed when all deferreds are resolved
                //do your task with contents
            });
        })
    }
    

    This is just a demo how to use promises. In real applications, you have to take care of errors by using deferred.reject and handle it in the second callback to $.when

提交回复
热议问题