【问题标题】:JS Increment not updating in for loop of while using gcs API使用gcs API时,JS增量未在for循环中更新
【发布时间】:2021-10-31 14:59:52
【问题描述】:

我想创建一个仅在 GCS 上复制所有文件时运行的函数。 运行 createNewTemplateFolder 函数时,“copiedFileAmout”没有更新。

这是点击功能的代码

const fileNamesToCopy = ['index.html', 'main.css','script.js','video.js','videocss.css'];
const loopFiles = async(request,response) =>{
    console.log(request.body)
    for (const fileNameEach of fileNamesToCopy) {
        const fileName = fileNameEach;
        // console.log(fileName)
        createNewTemplateFolder(bucketName, originalFolder + fileName,bucketName, newFolderPath + fileName, newFolderPath);      
    }   
      
    response.send("Folder Created ok.")

然后循环遍历 GCS 上的文件并复制到新文件夹。

const createNewTemplateFolder = async (srcBucketName, srcFilename, destBucketName,destFileName, destFilePath) =>{
    // Copies the file to the new folder
    let copiedFileAmout = 0;
    await storage
      .bucket(srcBucketName)
      .file(srcFilename)
      .copy(storage.bucket(destBucketName).file(destFileName))
      .then(() =>{
        console.log('copy done '+ destFileName)
        copyFileStatus = true;
        copiedFileAmout++  /// this is not working
      })
      .catch((err) =>{
        console.log(err)
        copiedFileAmout++
      })
      
    if(copiedFileAmout === 5){
        uploadCombineDelete(destFilePath) // This function should only run once when all 5 files is copied
    }   

在谷歌上搜索但不确定 Promise 是否无法运行增量。 希望能得到这方面的建议,谢谢!

【问题讨论】:

  • 为什么不在循环之后将呼叫移至uploadCombineDelete?这样,在所有文件都被复制后,它肯定会被调用,如果它有正确的值,你不必检查任何变量?

标签: javascript node.js google-cloud-storage google-api-nodejs-client


【解决方案1】:

您必须在函数之外(全局范围)声明变量copyedFileAmout。

let copiedFileAmout = 0;
const fileNamesToCopy = ['index.html', 'main.css','script.js','video.js','videocss.css'];
const loopFiles = async(request,response) =>{
....
....

然后删除该行

let copiedFileAmout = 0; 

来自函数createNewTemplateFolder

【讨论】:

  • @Carol Chaw,如果这回答了您的问题,请告诉我们?
  • 哦,奇怪的是,我一开始就将 'copiedFileAmout' 声明为全球性的,但它无法正常工作......但在你回答这个问题后现在工作正常,非常感谢!
【解决方案2】:

你有两个选择:

在函数之外声明copyedFileAmount,这样双方都可以访问它

let copiedFileAmount = 0;

或者一种不太有利的方法,只需将当前变量的声明从 let 更改为 var ,这样可以提供更大的范围。

var copiedFileAmount = 0;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-10
    • 2016-01-29
    • 2021-12-17
    • 2011-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多