【问题标题】:Calling a function that contains a promise from another function调用包含来自另一个函数的承诺的函数
【发布时间】:2020-03-18 04:42:01
【问题描述】:

我正在尝试学习如何在 NodeJs 中使用 Promise,并且我正在使用 AWS-SDK 库来访问 S3 对象。我的目标是从init() 函数中调用readFromS3() 函数并打印出文件的内容。但是,我没有得到我想要的结果,如下所示init() 中的第一个 console.log 语句所示。我了解承诺不完整,希望您对我如何阻止执行提出建议,直到 news 对象不为空??

const AWS = require('aws-sdk');

const S3 = new AWS.S3({});

const CONFIG = {
  init() {
    const news = CONFIG.readFromS3();
    console.log('These are the file contents ' + JSON.stringify(news));
    console.log('THIS IS THE END. This should only print after news have been read from S3');
  },

  readFromS3() {
    // set parameters for reading S3 files
    const options = {
      Bucket: 'my-bucket',
      Key: 'myFile.txt'
    };

    // create a promise to read from S3
    const readS3Promise = S3.getObject(options).promise();

    // start reading from s3
    readS3Promise
      .then(function(data) {
        return JSON.parse(data.Body);

        });
      })
      .catch(function(error) {
        console.log('ERROR: Cannot read from S3');
        throw error;
      });
  }
};

CONFIG.init();

但是,不幸的是,我目前的输出是这样的:

These are the SPECS undefined
THIS IS THE END. This should only print after news have been read from S3
{... // JSON data from S3 printed out

【问题讨论】:

    标签: javascript node.js promise


    【解决方案1】:

    您需要从 read 方法返回您的承诺,并在 init 函数中等待该调用,以便获得输出。像这样的

    const AWS = require('aws-sdk');
    
    const S3 = new AWS.S3({});
    
    const CONFIG = {
      async init() {
        const news = await CONFIG.readFromS3();
        console.log('These are the file contents ' + JSON.stringify(news));
        console.log('THIS IS THE END. This should only print after news have been read from S3');
      },
    
      readFromS3() {
        // set parameters for reading S3 files
        const options = {
          Bucket: 'my-bucket',
          Key: 'myFile.txt'
        };
    
        // create a promise to read from S3
        const readS3Promise = S3.getObject(options).promise();
    
        // start reading from s3
        return readS3Promise
          .then(function(data) {
            return JSON.parse(data.Body);
    
            });
          })
          .catch(function(error) {
            console.log('ERROR: Cannot read from S3');
            throw error;
          });
      }
    };
    
    CONFIG.init();
    

    【讨论】:

      猜你喜欢
      • 2017-03-26
      • 1970-01-01
      • 1970-01-01
      • 2019-05-27
      • 1970-01-01
      • 2020-01-13
      • 2020-08-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多