问题:在Node.js中将变量值发送到显示控制器时出现问题。

huangapple go评论78阅读模式
英文:

nodejs problem sending the variable value to show controller

问题

-- model--

class GloParameter {

    static findGlo(gloFunction, gloCode, gloValue, cb) {
        db.query(findGloParameterFCVActiveQuery, gloFunction, gloCode, gloValue, (err, res) => {
            if (err) {
                logger.error(err.message);
                cb(err, null);
                return;
            }
            if (res.length) {
                cb(null, res[0]);
                return;
            }
            cb({ kind: "not_found" }, null);
        })
    }

}

module.exports = GloParameter;

-- controller--

exports.serviceX = (req, res) => {

    const xx1 = GloParameter.findGlo(['withdraw_money_time', 'withdraw_money_time', 'start'], (err, data) => {
        console.log('xxxxxxx', data[0].glo_info1)
        return data[0].glo_info1
    })

    res.status(200).send({
        status: 'success',
        data: xx1

    });

    return
}

-- db --

const findGloParameterFCVActive = `
SELECT * FROM glo_parameter WHERE glo_function = ? AND glo_code = ? AND glo_value = ? AND glo_status = 'active'
`

module.exports = {
    findGloParameterFCVActive
};

Call Api

enter image description here

response API is parameter data : .....

Troubleshooting the display of results

英文:

nodejs problem sending the variable value to show controller

-- model--

class GloParameter {

    static findGlo(gloFunction, gloCode, gloValue, cb) {
        db.query(findGloParameterFCVActiveQuery, gloFunction, gloCode, gloValue, (err, res) => {
            if (err) {
                logger.error(err.message);
                cb(err, null);
                return;
            }
            if (res.length) {
                cb(null, res[0]);
                return;
            }
            cb({ kind: "not_found" }, null);
        })
    }

}

module.exports = GloParameter;

-- controller--

exports.serviceX = (req, res) => {

    const xx1 = GloParameter.findGlo(['withdraw_money_time', 'withdraw_money_time', 'start'], (err, data) => {
        console.log('xxxxxxx', data[0].glo_info1)
        return data[0].glo_info1
    })

    res.status(200).send({
        status: 'success',
        data: xx1

    });

    return
}

-- db --

const findGloParameterFCVActive = `
SELECT * FROM glo_parameter WHERE glo_function = ? AND glo_code = ? AND glo_value = ? AND glo_status = 'active'
`

module.exports = {
    findGloParameterFCVActive
};

Call Api

enter image description here

response API is parameter data : .....

Troubleshooting the display of results

答案1

得分: 0

问题在于你正在尝试从异步回调函数中返回一个值,而在Node.js中这是不可能的。回调函数在声明它的函数返回后的某个时间执行,所以回调函数无法返回到任何地方。

为了解决这个问题,你需要采用一种不同的方法,比如使用 promises 或者 async/await 语法。

例如:

/* 模型 */
const { query, findGloParameterFCVActive } = require("./db");
const util = require("util");
const queryAsync = util.promisify(query);

class GloParameter {
  static async findGlo(gloFunction, gloCode, gloValue) {
    try {
      const data = await queryAsync(findGloParameterFCVActiveQuery, [
        gloFunction,
        gloCode,
        gloValue,
      ]);
      if (!data.length) {
        throw { kind: "not_found" };
      }
      return data;
    } catch (err) {
      logger.error(err.message);
      throw err;
    }
  }
}

module.exports = GloParameter;

/* 控制器 */
exports.serviceX = async (req, res) => {
  try {
    const data = await GloParameter.findGlo(
      "withdraw_money_time",
      "withdraw_money_time",
      "start",
    );
    const xx1 = data[0].glo_info1;
    console.log("xxxxxxx", xx1);
    res.status(200).send({
      status: "success",
      data: xx1,
    });
  } catch (error) {
    console.error(error);
    res.status(500).send({
      status: "error",
      message: error.message,
    });
  }
}

然后,我认为问题在于你的 db.query 函数没有返回一个 promise,而是将回调函数作为最后一个参数。因此,你无法在其上使用 await,因为 await 只能用于 promises。

要解决这个问题,你需要将你的 db.query 函数包装在一个 promise 中,并在回调函数内部解析或拒绝它。例如:

/* db 文件 */

const query = (sql, ...params) => {
  return new Promise((resolve, reject) => {
    db.query(sql, ...params, (err, res) => {
      if (err) {
        reject(err);
      } else {
        resolve(res);
      }
    });
  });
};

const findGloParameterFCVActive = `
  SELECT * FROM glo_parameter WHERE glo_function = ? AND glo_code = ? AND glo_value = ? AND glo_status = 'active'
`;

module.exports = {
  query,
  findGloParameterFCVActive,
};
英文:

The problem is that you are trying to return a value from an asynchronous callback function, which is not possible in Node.js. The callback function is executed some time after the function in which it was declared has returned, so there is nowhere for the callback function to return to.

To solve this problem, you need to use a different approach, such as using promises or async/await syntax.

For example:

/* MODEL */
const { query, findGloParameterFCVActive } = require("./db");
const util = require("util");
const queryAsync = util.promisify(query);

class GloParameter {
  static async findGlo(gloFunction, gloCode, gloValue) {
    try {
      const data = await queryAsync(findGloParameterFCVActiveQuery, [
        gloFunction,
        gloCode,
        gloValue,
      ]);
      if (!data.length) {
        throw { kind: "not_found" };
      }
      return data;
    } catch (err) {
      logger.error(err.message);
      throw err;
    }
  }
}

module.exports = GloParameter;

/* CONTROLLER */
exports.serviceX = async (req, res) => {
  try {
    const data = await GloParameter.findGlo(
      "withdraw_money_time",
      "withdraw_money_time",
      "start",
    );
    const xx1 = data[0].glo_info1;
    console.log("xxxxxxx", xx1);
    res.status(200).send({
      status: "success",
      data: xx1,
    });
  } catch (error) {
    console.error(error);
    res.status(500).send({
      status: "error",
      message: error.message,
    });
  }
}

Then, I think the problem is that your db.query function does not return a promise, but takes a callback function as the last argument. Therefore, you cannot use await with it, because await only works with promises.
To fix this problem, you need to either wrap your db.query function in a promise and resolve or reject it inside the callback function. For example:

/* db File */

const query = (sql, ...params) => {
  return new Promise((resolve, reject) => {
    db.query(sql, ...params, (err, res) => {
      if (err) {
        reject(err);
      } else {
        resolve(res);
      }
    });
  });
};

const findGloParameterFCVActive = `
  SELECT * FROM glo_parameter WHERE glo_function = ? AND glo_code = ? AND glo_value = ? AND glo_status = 'active'
`;

module.exports = {
  query,
  findGloParameterFCVActive,
};

huangapple
  • 本文由 发表于 2023年7月4日 22:20:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76613584.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定