Home > Back-end >  google drive api - 'await' has no effect on this expression
google drive api - 'await' has no effect on this expression

Time:07-09

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)
}

    }

};

CodePudding user response:

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

CodePudding user response:

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

}


};

  • Related