异步上传多个文件到谷歌云存储桶 [英] async upload multiple files to google cloud storage bucket

查看:175
本文介绍了异步上传多个文件到谷歌云存储桶的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用NodeJS将多个文件上传到Google Cloud Storage存储桶.我希望先上传所有文件,然后再继续.我尝试了几种方法,但似乎无法正确完成.

I'm trying to upload multiple files to a Google Cloud Storage bucket using NodeJS. I want all files to be uploaded before continuing. I tried several approaches but I can't seem to get it right.

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');

这给了我以下输出,这不是我期望的.为什么在上传文件后不执行完成上传"日志?

This gives me the following output, which is not what I expect. Why is the 'finished uploading' log not executed after uploading the files?

start uploading
finished uploading
image1.jpeg uploaded
image2.jpeg uploaded
image3.jpeg uploaded

推荐答案

async/await不适用于forEach和其他数组方法.

async/await doesn't work with forEach and other array methods.

如果您不需要顺序上传(可以并行上传文件),则可以创建一个Promises数组,然后使用Promise.all()一次执行所有文件.

If you don't need sequential uploading (files can be uploaded in parallel) you could create an array of Promises and use Promise.all() to execute them all at once.

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');

这篇关于异步上传多个文件到谷歌云存储桶的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆