在 "For Loop" 中上传到 Google 云存储(异步)

Upload to Google Cloud Storage in a "For Loop" (async)

我是 Javascript 的新手。我正在尝试制作一个将图像上传到 Google 云存储的循环。使用此代码,可以正确上传图像。问题是上传后 路径 (URL) 没有保存在数据库中。

我尝试使用异步和等待。但是,我不明白它是如何工作的。 我希望在保存之前完成 for 循环和里面的所有内容 post。

提前谢谢你,

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