Waiting for promise in for loop

后端 未结 2 347
感情败类
感情败类 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:24

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

提交回复
热议问题