问题:
我编写了一个函数来确定某个存储桶是否存在。如果存在,我将向我的存储桶中上传一些东西,否则我将创建所述存储桶,然后继续上传我的东西。
但是我的工作流程有些麻烦。如果我的存储桶不存在。与//upload my stuff
能够创建我的存储桶相比,到达ensureBucketExists()
部分的速度更快。
来源:
Documentation of AWS
Create S3 Bucket if None Exists
How do I test if a bucket exists on AWS S3
我的代码:
let s3BucketName = 'myBucket';
const s3 = new AWS.S3({
// Connection
});
const uploadToS3Bucket = () => {
ensureBucketExists();
// upload my stuff...
}
const ensureBucketExists = () => {
let bucketParams = {
Bucket: s3BucketName
};
s3.headBucket(bucketParams, function(headError) {
if (!headError) return;
s3.createBucket(bucketParams, function(createError) {
if (!createError) console.log(`Created new ${s3BucketName}.`)
});
});
};
uploadToS3Bucket();
async
和await
,但是我不知道它们,并且似乎在正确实现它们方面遇到问题。答案 0 :(得分:1)
您对async
和await
的假设是正确的。作为讲座,我可以向您推荐有关asynchronous Programming原理的这一章。
为了实现您的预期,我增强了代码:
let s3BucketName = 'myBucket';
const s3 = new AWS.S3({
// Connection
});
const uploadToS3Bucket = async () => {
await ensureBucketExists();
// upload my stuff...
}
const ensureBucketExists = async () => {
let bucketParams = {
Bucket: s3BucketName
};
await s3.headBucket(bucketParams, function(headError) {
if (!headError) return;
s3.createBucket(bucketParams, function(createError) {
if (!createError) console.log(`Created new ${s3BucketName}.`)
});
});
};
uploadToS3Bucket();