【问题标题】:How to proper wait for a return before making any action?在采取任何行动之前如何正确等待退货?
【发布时间】:2019-04-09 11:16:59
【问题描述】:

我正在为一些等待/异步功能而苦苦挣扎。所以我有以下功能,pdfDataundefined 没有什么不同;我想要做的是,在创建 pdf 文件的所有过程用 s3 对其进行签名后,将其上传到 s3,然后将其从 temp 文件夹中删除以返回状态和要下载的 url。

谁能告诉我我错过了什么?

const pdfData = await pdf
  .create(content, options)
  .toFile(`./src/services/temp/${fileName}`, async function(error, result) {
    if (error) return console.log(error);

    const file = result.filename;
    // requestSignS3
    const awsSign = await signS3(
      `statements/${fileName}`,
      "application/pdf"
    );
    // upload document to S3
    const uploadStatus = await uploadDocumentToS3(awsSign, file);
    // delete file from temp folder
    fs.unlink(file, err => {
      if (err) throw err;
    });
    // set data to return
    const data = {
      status: uploadStatus,
      url: awsSign.url
    };

    return data;
  });

console.log(pdfData);

【问题讨论】:

  • 只是一个健全性检查问题...您的await pdf ... 在异步函数中吗?
  • 是的,这个函数都在try catch里面
  • ?? try/catch 不是异步函数
  • 是的,很抱歉,try catch 被包装在异步函数中

标签: javascript


【解决方案1】:

我看到 promise(或 async-await)配方与回调配方混合在一起。不要。

  1. toFile 是否返回承诺?如果是这样,那么我们几乎已经完成了:
const pdfFile = await pdf
  .create(content, options)
  .toFile(`./src/services/temp/${fileName}`);

const pdfData = await /* everything async you want to do with pdfFile goes there */(pdfFile);
  1. 如果toFile 没有返回承诺,您需要使用promisify 库或手动承诺它。它基本上看起来像这样:
const toFilePromise = new Promise(function(reject, resolve) => {
    pdf.create(content, options)
        .toFile(`./src/services/temp/${fileName}`, function(error, result) {
            if (error) {
                reject(error);
            } else {
                resolve(result);
            }
        })
});

现在,toFilePromise 是可以等待的。之后,您可以提取文件名、await signS3( 等。

【讨论】:

  • 所以我使用html-pdf 将车把渲染为pdf 和.toFile 我可以看到有两个参数export interface CreateResult { toBuffer(callback: (err: Error, buffer: Buffer) => void): void; toFile(callback: (err: Error, res: FileInfo) => void): void; toFile(filename?: string, callback?: (err: Error, res: FileInfo) => void): void; toStream(callback: (err: Error, stream: fs.ReadStream) => void): void; }
  • 编辑了更多细节。
猜你喜欢
  • 2014-05-02
  • 2019-07-04
  • 1970-01-01
  • 2014-03-19
  • 1970-01-01
  • 2016-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多