我正在尝试使用NodeJS将多个文件上传到Google Cloud Storage存储桶。我希望先上传所有文件,然后再继续。我尝试了几种方法,但似乎无法正确完成。
const jpegImages = await fs.readdir(jpegFolder);
console.log('start uploading');
await jpegImages.forEach(async fileName => {
await bucket.upload(
path.join(jpegFolder, fileName),
{destination: fileName}
).then( () => {
console.log(fileName + ' uploaded');
})
})
console.log('finished uploading');
这给了我以下输出,这不是我期望的。为什么在上传文件后不执行“完成上传”日志?
start uploading
finished uploading
image1.jpeg uploaded
image2.jpeg uploaded
image3.jpeg uploaded
答案 0 :(得分:4)
async
/ await
不适用于forEach
和其他数组方法。
如果您不需要顺序上传(可以并行上传文件),则可以创建一个Promises数组,并使用Promise.all()
一次执行所有操作。
const jpegImages = await fs.readdir(jpegFolder);
console.log('start uploading');
await Promise
.all(jpegImages.map(fileName => {
return bucket.upload(path.join(jpegFolder, fileName), {destination: fileName})
}))
.then(() => {
console.log('All images uploaded')
})
.catch(error => {
console.error(`Error occured during images uploading: ${error}`);
});
console.log('finished uploading');