简体   繁体   English

node.js-结合两个承诺

[英]node.js - Combining 2 Promises

I have to create a file upload which stores files in an amazon S3 bucket, and then writes info into a database. 我必须创建一个文件上传,将文件存储在Amazon S3存储桶中,然后将信息写入数据库。

  router.post('/report', upload.single('file'), function(req, res, next) {
    reportService
      .uploadReport(req.body, req.file)
      .then(data => {
        res.send(data);
      })
      .catch(err => {
        res.send(err);
      });
  });

This piece of code handles the call. 这段代码处理了调用。 It triggers the following code. 它触发以下代码。

function uploadReport(report, file) {
  var objectParams = { Bucket: bucketName, Key: file.filename, Body: '' };
  var fs = require('fs');
  var fileStream = fs.createReadStream(file.path);
  fileStream.on('error', function(err) {
    console.log('File Error', err);
  });
  objectParams.Body = fileStream;
  return new Promise((resolve, reject) => {
    s3.putObject(objectParams)
    .promise()
    .then(
      data => {
        resolve(this.addReport(report, data.Location)
          .then(response => resolve(response))
          .catch(err => {
            reject(err);
          })
        );
      },
      err => {
        reject(err);
      }
    );
  });
}

This piece of code uploads the file to my s3 bucket, after the upload is finished, it calls the save report function which writes into the database. 这段代码将文件上传到我的s3存储桶,上传完成后,它将调用save report function ,该save report function将写入数据库。

function addReport(report, url) {
  return new Promise((resolve, reject) => {
    reportModel
      .addReport(report, url)
      .then(report => {
        resolve(report);
      })
      .catch(err => {
        reject(err);
      });
  });
}

I know my 2 promises work separately, but combining them into 1 promise doesn't trigger any function. 我知道我的2个承诺分别工作,但是将它们组合成1个承诺不会触发任何功能。

How can I correctly combine them into 1 promise? 我如何正确地将它们组合成1个诺言?

It looks like you are violating the What is the explicit promise construction antipattern and how do I avoid it? 看来您违反了什么是显式promise构建反模式,如何避免呢? . You are resolving a Promise with a Promise. 您正在用承诺解决承诺。 Instead, you want to just return the Promise: 相反,您只想返回Promise:

return s3
    .putObject(objectParams)
    .promise()
    .then(data => this.addReport(report, data.location));

您将必须返回addReport ,然后在then回调中解析/拒绝原始addReport

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM