在实现另一个Promise的for循环后,如何解决Promise?

时间:2019-03-27 19:07:49

标签: javascript node.js promise es6-promise pdf.js

我正在Promise中使用Mozilla的PDF.js模块,以便将每个PDF页面转换为JPG图像。我的代码在fs模块的帮助下创建了文件图像,并与Promise模块上的promisify函数一起用作utils。此时,代码可以正常运行,但是我在其后放置了一个Resolve函数,并且没有被触发,并且Promise处于挂起状态。我应该把决心放在哪里?

我已经在函数的末尾进行了尝试,但是我感到我处理Promise的方式没有完全执行,并且我sto之以鼻,因为{{ 1}},以便使 PDF.js 模块正常工作

Promise

这是我在控制台上得到的答复

const CanvasFactory = require('./../../lib/canvas/canvas');
const pdfjsLib = require('./../../lib/pdf.js/node_modules/pdfjs-dist');

const fs = require('fs');
const { promisify } = require('util');

const writeFile = promisify(fs.writeFile);
const convertPDF2PNG = (pdfFilePath) => new Promise((resolve, reject) => {
  const loadingTask = pdfjsLib.getDocument(pdfFilePath);
  loadingTask.promise.then((pdf) => {
    const maxPages = pdf.numPages;
    const convertPDFPromises = [];
    for (let i = 1; i <= maxPages; i += 1) {
      const page = pdf.getPage(i);
      convertPDFPromises.push(page.then(page => {
        const viewport = page.getViewport({ scale: 1.0 });
        const canvasFactory = new CanvasFactory();
        const canvasAndContext = canvasFactory.create(viewport.width, viewport.height);
        const renderContext = {
          canvasContext: canvasAndContext.context,
          viewport,
          canvasFactory,
        };
        const renderTask = page.render(renderContext);
        renderTask.promise.then(() => {
          const image = canvasAndContext.canvas.toBuffer();
          writeFile(`temporal/output${i}.jpg`, image)
            .then(() => {
              // TODO: add query to insert images in Database
              console.log(`File ${i} added`);
            })
            .catch(writeErr => {
              console.error(writeErr)
              reject(writeErr);
            });
          })
          .catch(err => {
            console.error(err);
            reject(err);
          }); 
      }));
    }
  })
  .catch(reason => {
    console.error(reason);
    reject(reason);
  });
  resolve();
});

我想知道为什么File 2 added File 3 added File 1 added 没有得到解决。

0 个答案:

没有答案