【发布时间】: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