Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

144
Visualizações
google drive api - 'await' has no effect on this expression

I have seen countless tutorials online with almost identical code to mine simply putting await infront of the google drive call.

Yet any google call i try add 'await' infront of i get the error:

'await' has no effect on this type of expression

The code DOES RUN SUCCESSFULLY, but we are getting race conditions because the await is not being respected.

Sample Code

// Initialize a service account with the key file and scope needed.
// Use it for or Google Drive authorization.
const KEYFILEPATH = 'credentials.json';
const SCOPES = ['https://www.googleapis.com/auth/drive'];
const gal = require('google-auth-library');
const { google } = require('googleapis');
const auth = new gal.GoogleAuth({
  keyFile: KEYFILEPATH,
  scopes: SCOPES
});
const drive = google.drive({ version: "v3", auth });


//-------------------------------------------------------------------------------------------------------
//
async function writeFileFromPath(srcPath, dstFolderId, ext, fileName) {

    run().catch(console.error.bind(console));

    async function run() {
        try{



    console.log("Using File Path: ",srcPath);


  if (fileName == '') {
    fileName = srcPath.match(/[\w()-.]+\.[\w]+/g)[0];  // Extract just the filename
  }

  console.log("Using File Name: ",fileName);

  if (ext == '') {
    ext = fileName.match(/[\w]+$/g)[0];
  }

  let mimeType = mimeTypes[ext];

  if (mimeType == '') {
    mimeType = 'text/plain';
  }

  console.log("Using MIME Type: ",mimeType);

  let fileMeta = {
    'name': fileName,
    'parents': [dstFolderId]
  };

  let media = {
    mimeType: mimeType,
    body: fs.createReadStream(srcPath)
  };

// This await does not actually work and code runs ignoring it
  let driveResp =  await drive.files.create({
    supportsTeamDrives: true,
    resource: fileMeta,
    media: media,
    fields: 'id'
  });

  //console.log("Write Call Resp: ",driveResp);
  let fileCreated = false;

  if(typeof driveResp.data !== "undefined"){
    if(typeof driveResp.data.id !== "undefined"){
        console.log(`Created file with id: ${driveResp.data.id}`)
        fileCreated = true;
        return({ status: 200, statusText: `Created file with id: ${driveResp.data.id}` });
    }
  }
  if(!fileCreated){
    console.log(`Failed to create file: ${driveResp}`)
    return({ status: 400, statusText: `File was not created: ${driveResp}` });
  }


} catch (e){
    logger.addLog("googleDrive", "alert", "Unhandled Err: " + e);
    console.log("writeFileFromPath Error Caught: ",e.message);
    return(e.message)
}

    }

};

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Not entirely sure what i did to remedy the issue, but this is a working example thank you for the suggestions guys hope this helps someone else

async function writeFileFromPath(srcPath, dstFolderId, ext, fileName) {

  
try{



    console.log("Using File Path: ",srcPath);

    // if no ext passed in, try to parse from the file (multer does not add ext to files it saves so need this)
    if (fileName == '') {
    fileName = srcPath.match(/[\w()-.]+\.[\w]+/g)[0];  // Extract just the filename
    }

    console.log("Using File Name: ",fileName);

    // if no ext passed in, try to parse from the file (multer does not add ext to files it saves so need this)
    if (ext == '') {
    ext = fileName.match(/[\w]+$/g)[0];
    }

    let mimeType = mimeTypes[ext];

    if (mimeType == '') {
    mimeType = 'text/plain';
    }

    console.log("Using MIME Type: ",mimeType);

    let fileMeta = {
    'name': fileName,
    'parents': [dstFolderId]
    };

    let media = {
    mimeType: mimeType,
    body: fs.createReadStream(srcPath)
    };

    //This await claims it does not work but it does, if you remove call will fail every time
    let driveResp = await drive.files.create({
    supportsTeamDrives: true,
    resource: fileMeta,
    media: media,
    fields: 'id'
    });



        function processResponse(driveResp){
        //console.log("DRIVE RESP DATA: ",driveResp)
        let fileCreated = false;

        if(typeof driveResp.data !== "undefined"){

            if(typeof driveResp.data.id !== "undefined"){
                
            console.log(`Created file with id: ${driveResp.data.id}`)
            fileCreated = true;

            return({ status: 200, statusText: `Created file with id: ${driveResp.data.id}` });

            }

        }

        if(!fileCreated){

        console.log(`Failed to create file: ${driveResp}`)
        
        return({ status: 400, statusText: `File was not created: ${driveResp}` });

        }

        }

    return(processResponse(driveResp));

} catch (e){

    logger.addLog("googleDrive", "alert", "Unhandled Err: " + e);
    console.log("writeFileFromPath Error Caught: ",e.message);

    return(e.message);

}


};

about 4 years ago · Juan Pablo Isaza Relatório

0

You might be getting the impression that the create function isn't awaited because the containing function at the top doesn't await run.

If the caller expects to await writeFileFromPath, it will be awaiting null (maybe you've attributed the warning to the wrong source line), and things that are expected begin sequentially after the google-drive create will begin right away.

async function writeFileFromPath(srcPath, dstFolderId, ext, fileName) {
  return await run().catch(console.error.bind(console));

  async function run() {
    // etc
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda