0

I am trying to update "documentCopyId" variable, but print undefined

function listFiles(auth) {
const drive = google.drive({ version: 'v3', auth });
const apiKey = 'xxxxx';
const paragraph = "Hello World";
let documentCopyId;

var copyTitle = "Copy Title";
let request = {
    name: copyTitle,
};

drive.files.copy({
    fileId: 'xxxx',
    resource: request,
}, (err, driveResponse) => {
    console.log('document from drive copy ' + driveResponse.data.id) //Print id
    documentCopyId = driveResponse.data.id;
});
    
 console.log('document from listFiles '+ documentCopyId); // print undefined
}

complete Log:

document from listFiles undefined

document from drive copy 1IjXkk5QgTNVT85xxxxxx

Julian Benavides
  • 320
  • 1
  • 11
  • 1
    Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Joachim Isaksson Jul 21 '21 at 19:17
  • Wrap your console.log in a setTimeout and increase the duration till it works /s – Kevin B Jul 21 '21 at 19:20

1 Answers1

3

It is because the code

console.log('document from listFiles '+ documentCopyId); // print undefined

doesn't wait until this code completing

drive.files.copy({
    fileId: 'xxxx',
    resource: request,
}, (err, driveResponse) => {
    console.log('document from drive copy ' + driveResponse.data.id) //Print id
    documentCopyId = driveResponse.data.id;
});

which means that

console.log('document from listFiles '+ documentCopyId)

executing before

documentCopyId = driveResponse.data.id;

And in that case, documentCopyId is undefined.

As a solution, you can to promisify driver.files.copy part, and resolve the needed value. Or do need manipulations in a callback of drive.files.copy.

For example, you can do something like this

const listFiles = async (auth) => {
    let documentCopyId;

    const driveResponse = await copyPromise('Copy Title');

    documentCopyId = driveResponse.data.id;

    console.log('document from listFiles ' + documentCopyId);
};

const copyPromise = (name) => {
    return new Promise((resolve, reject) => {
        try {
            const drive = google.drive({ version: 'v3', auth });
            const apiKey = 'xxxxx';
            const paragraph = 'Hello World';
            let request = {
                name
            };

            drive.files.copy(
                {
                    fileId: 'xxxx',
                    resource: request,
                },
                (err, driveResponse) => {
                    if (err) throw new Error(err);
                    console.log('document from drive copy ' + driveResponse.data.id);
                    resolve(driveResponse);
                }
            );
        } catch (error) {
            console.log('Error in copyPromise:', error);
            reject(error);
        }
    });
};


CyberEternal
  • 2,259
  • 2
  • 12
  • 31