Node.js模块:导出异步功能

时间:2019-06-14 06:10:10

标签: node.js asynchronous node-modules

given example中,演示了如何从自定义模块导出变量或函数。如何以类似方式导出异步函数,然后从app.js中调用它,例如:

// app.js

var things = require("./someThings");

await things.getSomeThingsAsync();

编辑:

上面的链接所指向的示例(有关Stackoverflow的答案)包含以下代码:

// someThings.js

(function() {
    var someThings = ...;

    ...

    module.exports.getSomeThings = function() {
        return someThings();
    }

}());

// main.js

var things = require("someThings");
...
doSomething(things.getSomeThings());

说在模块的封装函数内部,存在一个异步函数,您想将其公开给任何导入该模块的人。例如:

(function() {
    ...
    const doSomethingAsync = (time) => {
        return new Promise(resolve => {
            setTimeout(() => resolve(42), time)
        })
    }

    //const doSomething = async () => {
    async function doSomething () {
        let answer1 = await doSomethingAsync(3000)
        let answer2 = await doSomethingAsync(1000)
        return answer1 + answer2
    }
    ...
    /*module.exports.doSomething = function() {
        return doSomething();
    }*/
    module.exports.doSomething = async function() {
        return doSomething();
    }
}());

您将如何以类似于doSomething中原始答案的方式公开someThings函数-如何在导出函数时以这种方式更改所引用的答案,它可以让您使用await关键字吗?然后将其用作:

// app.js

var things = require("./someThings");

console.log(await things.doSomething());

我尝试了多种方法,但是我总是得到:

SyntaxError: await is only valid in async function

4 个答案:

答案 0 :(得分:1)

您可以尝试以下方法:


//yourModule.js

let yourModule={};
yourModule.you=async()=>{
    //something await...
}
modules.export = yourModule;


//app.js

let yourModule = require('<pathToModule>');

async function test()
{
    await yourModule.you();  //your Await hear
}

答案 1 :(得分:1)

您误解了错误。它说

  

SyntaxError:等待仅在异步函数中有效

不是“ 用于异步功能”

您的导出没有问题。根本不可能在标记为await的函数之外使用async。因此,该错误位于app.js中。应该是:

var things = require("./someThings");

async function app () {
    console.log(await things.doSomething());
}

app().then(() => console.log('done calling app()'));

答案 2 :(得分:0)

这可能是这个问题的duplicate

您可以简单地功能(或功能表达式)分配给 module.exports'的属性(或全部) >。

例如:

async function AsyncStuff () { ... }

module.exports.myAsyncThing = myAsyncStuff;

答案 3 :(得分:0)

尝试

--------------------------------------------------------------------------
id | user_id | placed_loan | cleared loan | plcd date | cld_date | status
--------------------------------------------------------------------------
1  |   2     |   5000.00   |    0.00      |  19/6/12 |          |   1 
2  |   2     |   0.00      |    4000.00   |          |  19/6/13 |   2
3  |   2     |   2000.00   |    0.00      |  19/6/14 |          |   1
4  |   3     |   4000.00   |    0.00      |  19/6/14 |          |   1
5  |   2     |   0.00      |    3000.00   |          | 19/6/14  |   2
6  |   3     |   0.00      |    2000.00   |          | 19/6/15  |   2 
-------------------------------------------------------------------------- 
相关问题