我是 JavaScript 新手。我正在尝试制作一个将图像上传到 Google Cloud Storage 的循环。使用此代码,图像已正确上传。问题在于路径 (URL) 未在上传后保存在数据库中。
我尝试使用异步和等待。但是,我不明白它是如何工作的。 我希望在保存帖子之前完成 for 循环和里面的所有内容。
提前谢谢您,
for (const [i, file] of files.entries()) {
newFileName = "img_" + Date.now() + "_" + file.originalname;
imagePath = getPublicUrl(newFileName);
myfile = bucket.file(newFileName);
stream = myfile.createWriteStream({
metadata: {contentType: file.mimetype},
resumable: false
});
sharp(file.buffer)
.resize({ width: 1080 })
.pipe(stream)
.on('finish', () => {
post.images.push(imagePath);
})
}
post.save();
最佳答案
您想要为每个请求创建一个待处理 Promise 数组,然后您可以将它们包装在 Promise 方法 Promise.all([<\PENDING PROMISES>]) 中。
示例:
// we'll push all the promises into this array:
const pendingPromises = []
for (const {i, file} of files.entries()) {
// just wrap it in a promise
// and push into the promise array:
pendingPromises.push(new Promise((resolve, reject) => {
// do everything the same as before for each iteration
newFileName = "img_" + Date.now() + "_" + file.originalname;
imagePath = getPublicUrl(newFileName);
myfile = bucket.file(newFileName);
stream = myfile.createWriteStream({
metadata: {contentType: file.mimetype},
resumable: false
});
sharp(file.buffer)
.resize({ width: 1080 })
.pipe(stream)
.on('finish', () => {
post.images.push(imagePath);
resolve(imagePath)
})
}))
}
// wait for all the async code to complete execution and resolve before saving the posts:
Promise.all(pendingPromises)
.then(imagePaths => post.save()) /*<-- all the promises resolved without errors, now you can save*/
.catch(() => console.log('well that didnt work...'))
关于javascript - 以 "For Loop"上传到 Google Cloud Storage(异步),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59037741/