node.js 如何从节点模块导出异步函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43168116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:08:12  来源:igfitidea点击:

How to export async function from a node module

node.jsasync-await

提问by Nicolai

I'm trying to write a node module, to handle my various db calls. I want to use async/await where ever I can, but I'm having some issues with it.

我正在尝试编写一个节点模块来处理我的各种 db 调用。我想尽可能使用 async/await,但我遇到了一些问题。

I've been using promises a bit, and export those functions fine. Example:

我一直在使用承诺,并且可以很好地导出这些功能。例子:

function GetUsernames() {
    return new Promise(function (resolve, reject) {
        sql.connect(config).then(function () {
            new sql.Request()
                .query("SELECT [UserName] FROM [Users] ORDER BY [LastLogin] ASC").then(function (recordset) {
                    resolve(recordset);
                }).catch(function (err) {
                    reject(err);
                });
        });
    });
}

And then I export in the following:

然后我导出以下内容:

module.exports = {
    GetUsernames: GetUsernames,
    GetScopes: GetScopes,
    UpdateToken: UpdateToken,
    SetOwner: SetOwner
};

But, how should I do this, with an async function, to use the async/await that is available in node7?

但是,我应该如何使用 async 函数执行此操作以使用 node7 中可用的 async/await?

Do I still just return a promise? I tried doing that, but when I then call it in my code, it doesn't work.

我仍然只是返回一个承诺吗?我尝试这样做,但是当我在代码中调用它时,它不起作用。

const db = require("dataprovider");
...
var result = await db.GetUsernames();

It gives me:

它给了我:

SyntaxError: Unexpected identifier

语法错误:意外的标识符

on the db name (works fine if I just use the promise functions, with then().)

在 db 名称上(如果我只使用 promise 函数和 then(),则工作正常。)

Maybe my google skills are terrible, but I haven't managed to google anything I could use, on this issue.

也许我的谷歌技能很糟糕,但我还没有设法在这个问题上用谷歌搜索任何我可以使用的东西。

How on earth do I make an async function, in my module, that I can await elsewhere?

我到底如何在我的模块中创建一个异步函数,我可以在其他地方等待?

回答by Kevin Williams

To turn on the await keyword, you need to have it inside an async function.

要打开 await 关键字,您需要将它放在异步函数中。

const db = require("dataprovider");
...
let result = getUserNames();

async function getUserNames() {
    return await db.GetUsernames();
}

See http://javascriptrambling.blogspot.com/2017/04/to-promised-land-with-asyncawait-and.htmlfor more information.

有关更多信息,请参阅http://javascriptrambling.blogspot.com/2017/04/to-promised-land-with-asyncawait-and.html

Also, just as an FYI, it a code convention to start function with lowercase, unless you are returning a class from it.

此外,正如仅供参考,除非您从中返回一个类,否则以小写字母开头函数的代码约定。

回答by Market Queue

async - await pattern really makes your code easier to read. But node do not allow for global awaits. You can only await an asynchronous flow. What you trying to do is to await outside async flow. This is not permitted. This is kind of anti-pattern for node application. When dealing with promises, what we actually do is generate an asynchronous flow in our program. Our program continue without waiting for promise. So you can export your functions as async but cannot await for them outside async flow. for example.

async - await 模式确实让您的代码更易于阅读。但是节点不允许全局等待。您只能等待异步流。您要做的是在异步流之外等待。这是不允许的。这是节点应用程序的一种反模式。在处理 promise 时,我们实际做的是在我们的程序中生成一个异步流。我们的计划继续进行,无需等待承诺。因此,您可以将函数导出为异步,但不能在异步流之外等待它们。例如。

const db = require('dataprovider');
...
let result = (async () => await db.GetUserNames())();
console.log(result); // outputs: Promise { <pending> }

Thus, async-await pattern works for async flow. Thus use them inside async functions, so that node can execute them asynchronously. Also, you can await for Promises as well. for example.

因此,异步等待模式适用于异步流。因此在异步函数中使用它们,以便节点可以异步执行它们。此外,您也可以等待 Promise。例如。

let fn = async () => await new Promise( (resolve, reject)=>{...} );
fn().then(...);

Here you have created async function 'fn'. This function is thenable. also you can await for 'fn' inside another async function.

在这里,您已经创建了异步函数“fn”。这个功能是可以的。您也可以在另一个异步函数中等待“fn”。

let anotherFn = async () => await fn();
anotherFn().then(...);

Here we are waiting for async function inside a async function. Async-Await pattern makes your code readable and concise. This is reflected in large projects.

这里我们在 async 函数中等待 async 函数。Async-Await 模式使您的代码可读且简洁。这反映在大型项目中。