Waiting for promise in for loop

一世执手 提交于 2019-11-29 18:14:00

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

you can use async/await

async function getText(data) {
    var contents = [];
    var pdf = await PDFJS.getDocument(data);

    var numPages = pdf.pdfInfo.numPages;

    for (var i = 1; i <= numPages; i++) {
      var page = await pdf.getPage(i);
      var content = await page.getTextContent();

      contents.concat(content.bidiTexts);      
    }    
}

Note that getText will return a promise, you can use async /await again to access the result or getText(data).then(result => console.log(result));

if you want to get the pages in parallel, use Promise.All then await for the .getContent() :

async function getText(data) {
  var pdf = await PDFJS.getDocument(data)
  var numPages = pdf.pdfInfo.numPages;

  var promises = [];

  for (var i = 1; i <= numPages; i++) {
    promises.push(pdf.getPage(i));
  }

  var result = await Promise.All(promises)
    .then(pages => pages.map(page => await page.getTextContent()));

  return result;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!