javascript - 以 "For Loop"上传到 Google Cloud Storage(异步)

标签 javascript node.js google-cloud-platform google-cloud-storage nodejs-stream

我是 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/

相关文章:

javascript - 我想在用户单击特定链接后在 div 弹出窗口中播放视频

javascript - 如何在一行中干燥我的 jQuery 代码

javascript - 类型错误 : callback is not a function -

node.js - socket.emit 不适用于其他打开的连接

node.js - 我如何在 Cypress 中使用流程?

mysql - 如何从 GCP 上的实例备份恢复单个数据库?

google-cloud-platform - 尝试注册免费试用

javascript - 'this'指的是什么?

javascript - 从 HTML 调用函数的变量作用域

go - GCP IoT Core 拒绝此 RSA_PEM 公钥并出错