我正在导入一个异步函数并尝试使用它

Ven*_*yla 2 asynchronous node.js promise

以下是我读取数据的异步函数

const fs = require('fs');

module.exports = {

    foo: async () => {
        const a = async () => {
            filedata = await fs.readFile('./scripts/pairs.json');
            console.log(filedata);
        }
        a()
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在导入第二个文件中的数据并尝试使用 setTimeout 但我失败了

var a = require('./scripts/2_fundAccounts')

app.get('/createaccount',(req,res) =>{
     console.log(setTimeout(()=>a.foo().then((i)=> console.log(i)),5000));
})
Run Code Online (Sandbox Code Playgroud)

我收到超时错误

超时 { _call: false, _idleTimeout: 5000, _idlePrev:

接下来我删除了 setTimout 并尝试了然后我变得未定义

app.get('/createaccount', (req, res) => {
    console.log(a.foo().then((i) => console.log(i)))
})
Run Code Online (Sandbox Code Playgroud)

接下来我更改了 2_fundaccounts 代码

等待一个()

我有

Server is listing on port 3000
Promise { <pending> }
(node:18637) [DEP0013] DeprecationWarning: Calling an asynchronous function without callback is deprecated.
undefined
Run Code Online (Sandbox Code Playgroud)

1)任何让承诺得到解决而没有任何错误的建议

2)请帮助我,我不想更改我的 2_fundacounts 代码,我没有 wrights

3)如果我必须更改 2_fundaccounts 告诉我什么以及如何做

小智 5

你用fs错了。它的方法是异步的,但它们基于回调。你的代码应该是这样的:

foo() {
    return new Promise((resolve, reject) => {
        fs.readFile('./scripts/pairs.json', (err, filedata) => {
            if (err) {
                reject(err);
            } else {
                resolve(filedata);
                console.log(filedata);
            }
        });
    });
}
Run Code Online (Sandbox Code Playgroud)

但是,如果您使用的是 Node 10 或更高版本,导入require('fs').promises可让您将其方法用作典型的异步函数:

const fs = require('fs').promises;

module.exports = {
    foo: async () => {
        const filedata = await fs.readFile('./scripts/pairs.json');
        console.log(filedata);
        return filedata;
    }
}
Run Code Online (Sandbox Code Playgroud)