javascript - 调用一个包含来自另一个函数的 Promise 的函数

标签 javascript node.js promise

我正在尝试学习如何在 NodeJs 中使用 Promise,并且正在使用 AWS-SDK 库来访问 S3 对象。我的目标是从 init() 函数中调用 readFromS3() 函数并打印出文件的内容。但是,我没有得到我想要的结果,如下所示,init() 中的第一个 console.log 语句。我知道 promise 并不完整,并且希望获得您关于如何阻止执行直到 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

最佳答案

您需要从 read 方法返回您的 promise ,并在 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();

关于javascript - 调用一个包含来自另一个函数的 Promise 的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60729787/

相关文章:

javascript - 将应用程序上传到 HEROKU 时出现问题,异步失败。 H12

javascript - 修改数据后 Vue.js 输入值不更新

javascript - 将 2 个图像与 node.js 和 gm 合并

javascript - 显式等待 isPresent 和 isDisplayed 导致未找到元素失败

node.js - nodejs sendMessage 函数如果失败 X 次

javascript - Highcharts 中的多个类别和系列

javascript - 为什么我的 CSS 文本缩放动画会创建 "curving"运动,如何消除它?

javascript - 一次在两个字段上的 firestore.where()

javascript - 我如何在 EmberJS 应用程序中使用 Jitsi Meet

javascript - Typescript: promise 的类型缩小