我正在尝试学习如何在 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/