简体   繁体   English

Node.js function 异步返回不等待

[英]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...我想我在理解 Node.js 中的等待/承诺时遇到问题,我以为我正确地实现了它,但它看起来不正确......

I have this function to get a list of files from my Google Drive:我有这个 function 从我的 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:这个 function 工作正常,但现在我尝试在我的 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.所以我的问题是,从getFiles()我总是得到Promise { <pending> }作为 console.log ......但在我的listFiles()中,我可以看到文件在await之后被正确打印......我真的不明白,在await之后, filesList应该准备好并解决。

What am I doing wrong here?我在这里做错了什么?

async function returns a promise , so you still have to await it async function 返回 promise ,所以你仍然需要await

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.一个 Promise 将使用异步 function 返回的值解析,或者被异步 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();

listFiles is correctly listed as being async , but in this case, getFiles should be async too - it needs to await the results of listFiles . listFiles被正确列为async ,但在这种情况下, getFiles也应该是 async - 它需要await 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM