【发布时间】:2022-02-14 20:23:31
【问题描述】:
我正在尝试完成以下任务:我需要从 url 下载图像,然后将其上传到 S3 存储并返回上传文件的位置。我正在使用 async/await 函数来完成任务,但它返回 Promise { pending } 并在几秒钟后返回位置,我想在 promise 解决后返回位置。这是我的代码:
// Space config
const spaceEndPoint = new AWS.Endpoint("fra1.digitaloceanspaces.com");
const s3 = new AWS.S3({
endpoint: spaceEndPoint,
accessKeyId: "xxxxxxxxx",
secretAccessKey: "xxxxxxxxxxxxxxxxx",
});
// Download image from url
const downloadImage = async (url) => {
try {
const file = axios
.get(url, {
responseType: "stream",
})
.then((res) => res.data)
.catch((err) => console.log(err));
return file;
} catch (err) {
console.log(err);
}
};
// Upload to space
const upload = async (fileUrl) => {
// Get file name from url
const fileName = path.basename(fileUrl);
// Path to save tmp file
const localFilePath = path.resolve(__dirname, "../downloads", fileName);
// Download file
const file = await downloadImage(fileUrl);
// Write file to disk
await file.pipe(fs.createWriteStream(localFilePath));
// Upload params
const params = {
Bucket: "sunday",
Body: fs.createReadStream(localFilePath),
Key: path.basename(fileName),
ContentType: "application/octet-stream",
ACL: "public-read",
};
const { Location } = await s3.upload(params).promise();
return Location;
};
console.log(
upload(
"https://i.pinimg.com/474x/e9/62/7c/e9627ce6fe731ba49597d3a83e21e398.jpg"
).then((data) => data)
);
// Result:
Promise { <pending> }
https://sunday.fra1.digitaloceanspaces.com/e9627ce6fe731ba49597d3a83e21e398.jpg
所以我想在承诺解决后返回位置。 提前感谢您的帮助!
【问题讨论】:
标签: javascript node.js axios fs