本地等待诺言

时间:2020-02-29 11:07:12

标签: node.js

我想要什么:

// db.js
const mariadb = require('mariadb');
module.exports = {
 conn: await mariadb.createConnection({ ... }) // mariadb returns a connection with a promise
};
// foo.js
const conn = require('./db').conn;

我在做什么:

// db.js
const mariadb = require('mariadb');
module.exports = {
 getConn: mariadb.createConnection({ ... }) // mariadb returns a connection with a promise
};
// foo.js
const getConn = require('./db').getConn;
(async()=>{
    const conn = await getConn;
    // ...
})();

我觉得很浪费。
有什么方法可以等待承诺直到出口?

1 个答案:

答案 0 :(得分:1)

top-level await(Node尚不支持)。

另请参阅why you may not want to do this