Nodejs 请问已经调用了return , 但是下面的步骤依然会执行,是异步还是逻辑出错?

Nodejs 请问已经调用了return , 但是下面的步骤依然会执行,是异步还是逻辑出错?

这是我的一个判断函数,如果发现条件成立则return到跳转链接。

function checkValue(req, res) {
  if (isNaN(req.body.goodsPrice) || isNaN(req.body.originalPrice)) {
    req.session.error = '商品价格必须为数字';
    console.log('..........................');
    return res.redirect('/server');
  }
}

然后再到这里调用这个函数,但是已经触发了条件并且return却依旧会往下执行。是异步导致吗?谢谢?

router.post('/server/:goods_id', function (req, res) {
...
  checkValue(req, res);
   var url = 'http://localhost:5001/admin/seller/goods/edit';
  var options = {
    url: url,
    headers: {
      'Cookie': 'session=' + req.cookies.session
    },
    form: goods
  };
  request.post(options, function (err, response, body) {
    if (err) {
      return console.log(err);
    }
    var data = JSON.parse(body);
    console.log(data);
  });
});

4 回复

在Node.js中,函数 checkValuereturn res.redirect('/server'); 语句仅会在当前函数内部返回,而不会阻止外部函数的继续执行。这是因为 Node.js 中的函数调用通常是同步的,除非显式地使用异步操作(如回调、Promise 或 async/await)。

示例代码分析

function checkValue(req, res) {
  if (isNaN(req.body.goodsPrice) || isNaN(req.body.originalPrice)) {
    req.session.error = '商品价格必须为数字';
    console.log('..........................');
    return res.redirect('/server');
  }
}

router.post('/server/:goods_id', function (req, res) {
  checkValue(req, res);
  
  var url = 'http://localhost:5001/admin/seller/goods/edit';
  var options = {
    url: url,
    headers: {
      'Cookie': 'session=' + req.cookies.session
    },
    form: goods
  };

  request.post(options, function (err, response, body) {
    if (err) {
      return console.log(err);
    }
    var data = JSON.parse(body);
    console.log(data);
  });
});

解释

在上面的代码中:

  1. checkValue 函数

    • 如果 req.body.goodsPricereq.body.originalPrice 不是数字,则设置错误信息并尝试重定向。
    • 使用 return res.redirect('/server'); 尝试提前结束 checkValue 函数。
  2. router.post 路由处理程序

    • 调用 checkValue(req, res);,但即使 res.redirect('/server') 被调用,它也不会阻止后续代码的执行。
    • 继续执行 request.post 方法,发送HTTP POST请求到指定URL。

解决方案

为了确保在满足条件时立即停止执行,可以使用 async/awaitPromise 来处理异步操作。以下是修改后的代码示例:

function checkValue(req, res) {
  if (isNaN(req.body.goodsPrice) || isNaN(req.body.originalPrice)) {
    req.session.error = '商品价格必须为数字';
    console.log('..........................');
    return res.redirect('/server');
  }
}

router.post('/server/:goods_id', async function (req, res) {
  await checkValue(req, res);

  if (res.finished) {
    // 如果重定向发生,则提前结束
    return;
  }

  var url = 'http://localhost:5001/admin/seller/goods/edit';
  var options = {
    url: url,
    headers: {
      'Cookie': 'session=' + req.cookies.session
    },
    form: goods
  };

  request.post(options, function (err, response, body) {
    if (err) {
      return console.log(err);
    }
    var data = JSON.parse(body);
    console.log(data);
  });
});

解释

  • 使用 async 关键字使路由处理程序成为异步函数。
  • 使用 await 等待 checkValue 函数完成。
  • 检查 res.finished 属性,如果重定向已发生,则提前结束函数。

通过这种方式,可以确保在满足条件时立即停止执行后续代码。


checkValue内部return了,调用checkValue的函数没有return啊

是因为checkValue没有next- -。 执行顺序 post('/server') -----> checkValue -----> redirect('/server') -----> checkValue -----> ... 这样当然会没玩没了。 按照我对你的业务逻辑的理解,应该这么写。

function checkValue(req, res, next) {
  if (isNaN(req.body.goodsPrice) || isNaN(req.body.originalPrice)) {
    req.session.error = '商品价格必须为数字';
    console.log('..........................');
    return res.redirect('/server');
  }
  next()
}

在你的代码中,checkValue 函数确实会在条件满足时返回 res.redirect('/server'),但 request.post 是一个异步操作,它不会阻止后续代码的执行。因此,即使 checkValue 返回了,request.post 依然会被执行。

如果你希望在 checkValue 返回后不再执行后续代码,你需要在 checkValue 中使用回调函数或 Promise 来控制流程。

以下是使用回调函数的示例:

function checkValue(req, res, callback) {
  if (isNaN(req.body.goodsPrice) || isNaN(req.body.originalPrice)) {
    req.session.error = '商品价格必须为数字';
    console.log('..........................');
    return res.redirect('/server');
  }
  callback(); // 继续执行
}

router.post('/server/:goods_id', function (req, res) {
  checkValue(req, res, () => {
    var url = 'http://localhost:5001/admin/seller/goods/edit';
    var options = {
      url: url,
      headers: {
        'Cookie': 'session=' + req.cookies.session
      },
      form: goods
    };
    request.post(options, function (err, response, body) {
      if (err) {
        return console.log(err);
      }
      var data = JSON.parse(body);
      console.log(data);
    });
  });
});

这样,只有当 checkValue 执行完毕且没有发生重定向时,才会继续执行 request.post

如果你熟悉 Promises,也可以使用它们来更好地控制异步流程。

回到顶部