Julian Benavides
Julian Benavides

Reputation: 330

How to update a variable NodeJs

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

Upvotes: 0

Views: 466

Answers (1)

CyberEternal
CyberEternal

Reputation: 2545

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


Upvotes: 3

Related Questions