从 NODEJS API 发送多个数组作为响应不等待响应

Sending multiple arrays from NODEJS API in response not wait for the response

我尝试了不同的方法来发送数组中的数据,但它显示为空。我确信这是因为响应在实际响应 return 之前触发。好吧,这是我的猜测!我可能错了..我想知道这样做的最佳做法?

我在负载中的预期结果:

data: {
allCountries: [{TotalCountries: 12}]
allStates: [{StateId: "15327", STR: "Form",…}, {StateId: "15326", STR: "Form",…},…]
AllCities: [,…]
AllCust: {Id: "1825",…}
}

现在,在 nodejs 控制器中,我有 4 个函数

exports.getAllDetails = async (req, res) => {
  
  if (!req.query.clientId) {
    return res.status(406).send({
      success: false,
      message: "ID is required"
    })
  }

  let id = req.query['custId'];
  let allCountries= await getAllCountries(req, res, id)
  // let allStates= this.getStates(req, res, id);
  // let allCities= this.getAllCities(req, res, id);
  // let custDetails= this.getCustDetails(req, res, id);


  return res.send({
    success: true,
    data:
    [allCountries]
    [allStates],
    [AllCities],
    [AllCust]
  })
}

现在我已经为所有人创建了单独的函数。即

async function getAllCountries(req, res, id) {

  let allCountries;

  allCountries= `SELECT query..`

  connection.query(allCountries, (err, result) => {

    if (result) {
      if (result.length > 0) {
        return result;
      } else {
        res.status(204).send({
          success: false,
          message: `No data found.`,
        });
      }
    }
  });
}

我得到的结果是空数组? 谁能告诉我最好的方法吗?

因为您正在尝试 return 来自回调函数的数据:

async function getAllCountries(req, res, id) {

  let allCountries;

  allCountries= `SELECT query..`

  connection.query(allCountries, (err, result) => {

    if (result) {
      if (result.length > 0) {
        return result; // this won't work because it is inside callback function.
      } else {
        res.status(204).send({
          success: false,
          message: `No data found.`,
        });
      }
    }
  });
}

您需要return承诺对象:

async function getAllCountries(id) {

  let allCountries;

  allCountries= `SELECT query..`

  return new Promise((resolve) => {
    connection.query(allCountries, (err, result) => {

    if (result) {
      if (result.length > 0) {
        resolve(result);
      } else {
        resolve(null);
      }
    }
    });
  });
}

还有你使用这个功能的地方:

  let allCountries= await getAllCountries(id);
  if (allCountries == null) {
      return res.status(204).send({
         success: false,
         message: `No data found.`,
      });
  }

我建议您开始使用 try/catch 来处理错误,而不是所有函数都传递参数 req/res,使用此解决方案您的代码将更具可读性。

function getAllCountries(req, res, id) {
  return new Promise((res, rej) => {
    let allCountries;
    allCountries = `SELECT query..`;
    connection.query(allCountries, (err, result) => {
      if (err) {
        rej(err);
      }

      if (result.length === 0) {
        rej({
          success: false,
          message: `No data found.`,
        });
      }
      res(result);
    });
  });
}

在你的主函数中:

exports.getAllDetails = async (req, res) => {
  if (!req.query.clientId) {
    return res.status(406).send({
      success: false,
      message: 'ID is required',
    });
  }

  try {
    let id = req.query['custId'];
    let allCountries= await getAllCountries(id)
    ...
  
  
    return res.send({
      success: true,
      data: {
        allCountries, //as you want this as array wrap the allCountries as [allCountries]
        ...
      }
    })
  } catch (err) {
    return res.status(400).send(err);
  }
};