如何异步返回sequelize实例?

时间:2018-07-13 23:04:24

标签: node.js sequelize.js

我似乎无法将sequelize文件中的service.js对象正确地传递给index.js的sequelize变量。

有什么地方不对吗?

index.js

let sequelize;
let contractModel;

(async () => {
    sequelize = await lambdaHelper.init(); //The issue is here
    contractModel = require('./models/Contract')(sequelize, Sequelize); 
})();

service.js

exports.init = async () => {
    let sequelize = await new Sequelize(process.env.FNI_DATABASE, process.env.FNI_USER, process.env.FNI_PASSWORD, {
        host: process.env.FNI_HOST,
        dialect: 'mysql',
        operatorsAliases: false,
        define: {
            timestamps: false,
            freezeTableName: true
        },

        pool: {
            max: 5,
            min: 0,
            acquire: 30000,
            idle: 10000
        }

    });
    return sequelize;
};

service2.js 以下代码可同步工作

exports.init = () => new Sequelize(process.env.FNI_DATABASE, process.env.FNI_USER, process.env.FNI_PASSWORD, {
    host: process.env.FNI_HOST,
    dialect: 'mysql',
    logging: false,
    operatorsAliases: false,
    define: {
        timestamps: false,
        freezeTableName: true
    },

    pool: {
        max: 5,
        min: 0,
        acquire: 30000,
        idle: 10000
    }

});

结果

  

*********** **************之前(节点:66912)UnhandledPromiseRejectionWarning:未处理的承诺被拒绝   (拒绝ID:1):TypeError:无法读取的属性'findAll'   未定义(节点:66912)[DEP0018] DeprecationWarning:未处理的承诺   不推荐使用。将来,应承诺拒绝   未处理将以非零退出终止Node.js进程   代码。

结果2

  

*********** **************之前(节点:66540)UnhandledPromiseRejectionWarning:未处理的承诺被拒绝   (拒绝ID:1):TypeError:无法读取的属性'findAll'   未定义(节点:66540)[DEP0018] DeprecationWarning:未处理的承诺   不推荐使用。将来,应承诺拒绝   未处理将以非零退出终止Node.js进程   码。执行中(默认):SELECT 1 + 1 AS结果TypeError:无法读取   未定义的属性“定义”       在module.exports

1 个答案:

答案 0 :(得分:1)

上面代码中的

await new Sequelize(...)期望new Sequelize返回一个诺言,但事实并非如此。有authenticate method可以做到这一点。

应该是:

exports.init = async () => {
    let sequelize = new Sequelize(...);
    await sequelize.authenticate();
    return sequelize;
};

确保始终正确处理承诺拒绝:

(async () => {
    sequelize = await lambdaHelper.init();
    contractModel = require('./models/Contract')(sequelize, Sequelize);
})().catch(console.error);