1

我尝试了许多让我的函数返回参数的变体,这样我只能在一个步骤完成时运行我的函数,但寻找不会让我陷入回调地狱的最佳方法。

我有以下功能

function convertPdfToImage(fileName) {

  return new Promise((resolve, reject) => {
    var pdfImage = new PDFImage(fileName+".pdf");

    pdfImage.convertFile().then(function (imagePaths) {
      var file = fs.createWriteStream(imagePaths);
      file.end();
      file.on("finish", () => { resolve(true); });
      file.on("error", reject);
      return resolve(true)
    });
  });
}

我在这里这样称呼:

Promise.all([convertPdfToImage('test2'), convertPdfToImage('test1')])})
    .then(function () {
      compareItems(codeId);
    });

这是 PromiseAll 中调用的方法

function convertPdfToImage(env: string, shareClassId: string[]) {

  return new Promise((resolve, reject) => {
    var pdfImage = new PDFImage("output/" + shareClassId + env + ".pdf");

    pdfImage.convertFile().then(function (imagePaths) {
      var file = fs.createWriteStream(imagePaths);
      file.end();
      file.on("finish", () => { resolve(true); });
      file.on("error", reject);
      return resolve(true)
    });
  });
}

无论我尝试什么问题,我都无法保证 compareItems 在 convertPdfToImage 之后运行(PromiseAll 已解决)

4

2 回答 2

0

Promise的 s 的结构并不正确,看看我的例子:

const fs = require("fs");

class PDFImage {
  constructor(filename) {
    this.filename = filename;
  }
  convertFile() {
    return new Promise((resolve, reject) => {
      resolve(`image-${this.filename}`);
    });
  }
}

function convertPdfToImage(fileName) {

  return new Promise((resolve, reject) => {

    new PDFImage(fileName).convertFile().then(imageFileName => {

      const file = fs.createWriteStream(imageFileName);
      file.end();

      file.on("error", (error) => {
        reject(error);
      });

      file.on("finish", () => {
        resolve(true)
      });
    });
  });
}

Promise.all([
  convertPdfToImage("first-file"),
  convertPdfToImage("second-file")
]).then(response => {
  console.log(response);
  console.log("files created, can be compared now.");
})

此代码将创建文件image-first-fileimage-second-file,并且只有在两个Promises 都被解析后,打印response并且在那里您可以调用compareItems.

于 2020-02-27T08:18:26.680 回答
0

你可能没有正确实现承诺,

function convertPdfToImage(fileName) {
  let pdfImage = new PDFImage(fileName+".pdf");
  return pdfImage.convertFile().then(function (imagePaths) {
    let file = fs.createWriteStream(imagePaths);
      file.end();
      file.on("finish", () => { resolve(true); });
      file.on("error", reject);
      return true 
  }).catch(err){
    console.log(err);
  }
} 

此外,使用异步/等待,

async function convertPdfToImage(fileName) {
  let pdfImage = new PDFImage(fileName+".pdf");
  try{
    const imagePaths = await pdfImage.convertFile();
    let file = fs.createWriteStream(imagePaths);
    file.end();
    file.on("finish", () => { resolve(true); });
    file.on("error", reject);
    return true 
  } catch(err){
    console.log(err);
  }
} 

另外,看到这个问题

于 2020-02-28T06:14:33.950 回答