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?
2 Answers 2
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();
3 Comments
getFiles(), you could still call it this waylistFiles 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();