codeKiller
codeKiller

Reputation: 5758

Node.js function async return not awaiting

I think I am having a problem understanding the await/promises in Node.js, I thought I was implementing it correctly but it does not look right...

I have this function to get a list of files from my Google Drive:

const listFiles = async () => {
    const filesList = await googleDrive.listFiles();
    filesList.forEach((file)=>{
        console.log(`File is ${file.name}`);
    });
    return filesList;
  }

This function works fine, but now I tried to call it like this in my main.js:

const listFiles = async () => {
    const filesList = await googleDrive.listFiles();
    filesList.forEach((file)=>{
        console.log(`File is ${file.name} with id`);
    });
    return filesList;
  }

const getFiles =() =>{
    const files = listFiles();
    console.log(files);
};


getFiles();

So my problem here is that, from getFiles()I always get Promise { <pending> } as a console.log...but in my listFiles(), I can see the files being printed correctly after the await....I do not really get it, after the await, the filesList should be ready and resolved.

What am I doing wrong here?

Upvotes: 1

Views: 50

Answers (2)

A McBride
A McBride

Reputation: 405

listFiles is correctly listed as being async, but in this case, getFiles should be async too - it needs to await the results of listFiles.

Your code should then look as follows:

const listFiles = async () => {
    const filesList = await googleDrive.listFiles();
    filesList.forEach((file)=>{
        console.log(`File is ${file.name} with id`);
    });
    return filesList;
  }

const getFiles = async () =>{
    const files = await listFiles();
    console.log(files);
};


getFiles();

Upvotes: 1

hgb123
hgb123

Reputation: 14891

async function returns a promise, so you still have to await it

Return value

A Promise which will be resolved with the value returned by the async function, or rejected with an exception thrown from, or uncaught within, the async function.

const listFiles = async () => {
    const filesList = await googleDrive.listFiles();
    filesList.forEach((file)=>{
        console.log(`File is ${file.name} with id`);
    });
    return filesList;
  }

const getFiles = async () =>{
    const files = await listFiles();
    console.log(files);
};


getFiles();

Upvotes: 2

Related Questions