【问题标题】:How to pass data from Helper Mysql Promises nodejs如何从 Helper Mysql Promises nodejs 传递数据
【发布时间】:2021-02-02 04:42:56
【问题描述】:

我从文件夹助手传递数据时遇到问题

数据库.js

const mysql = require('mysql2');

const pool = mysql.createPool({
    host: 'localhost',
    port:'3306',
    user: 'root',
    database: '',
    password: '',
    dateStrings: true
});

module.exports = pool.promise();

helper.js

const Master = require('../models/inspection');

module.exports = {
    getLokasi: function (x) {
        Master.fetchAll()
            .then(([result]) => {
                const hasil = result;
                return hasil;
            })
            .catch(err => console.log(err));
    }
}

模型检查.js

const db = require('../util/database');

module.exports = class Master {
    constructor(si_id) {
        this.si_id  = si_id;
        
    }

    static fetchAll() {
        return db.execute('SELECT * FROM mt_analisa_resiko');
    }

  };

控制器

const helpers = require('../../util/helpers');

exports.getInspectionDetail = (req, res, next) => {
    const test = helpers.getLokasi();
    console.log(test);
}

问题总是返回 undefined

但是当我在 helper.js 上使用 console.log(hasil) 时,它会返回数据。我如何从助手传递数据,以便我可以在控制器上使用数据。

【问题讨论】:

    标签: javascript node.js mysql2


    【解决方案1】:

    你需要返回承诺:

    module.exports = {
        getLokasi: function (x) {
            return Master.fetchAll()
                .then(([result]) => {
                    const hasil = result;
                    return hasil;
                })
                .catch(err => console.log(err));
        }
    }
    

    您应该能够访问返回的值:

    exports.getInspectionDetail = async (req, res, next) => {
        const result = await helpers.getLokasi();
        console.log(result);
    } 
    

    【讨论】:

    • 你能帮我如何兑现承诺吗?非常感谢
    • 仔细看看我的回答。我在Master.fetchAll() 之前添加了return。它应该可以正常工作。
    • 感谢您的帮助。当我检查它返回 Promise { }. 时,我已经更改了代码
    猜你喜欢
    • 2017-10-07
    • 1970-01-01
    • 1970-01-01
    • 2017-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多