我的异步请求不适用于快递

时间:2019-08-20 21:37:21

标签: javascript express asynchronous promise

我正在尝试将我的请求转换为异步调用,以便它们不会阻塞。

app.js

app.use(function(err, req, res, next) {
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};
  console.log(err);
  res.status(err.status || 500);
  res.json({ error: err.message });
});

路线

router.get(
  "/seatData/:seatNumber",
  [
    check("seatNumber")
      .matches(/^[0-9][a-z]$/i)
      .withMessage("must start with a number(0-9) and end with a letter")
  ],
  actions.fetch_seat
);

控制器

exports.fetch_seat = (req, res, next) => {
  Seat.getSeatByNumber(req.params.seatNumber, (err, seat) => {
    if (err) res.json(err);
    else res.json(seat);
  });
};

模型

Seat.findSeat = function(key, value) {
  return new Promise((resolve, reject) => {
    const seat = file.find(r => r[key] === value);
    if (!seat) {
      reject({
        error: true,
        message: "Seat not found",
        status: 404
      });
    }
    resolve(seat);
  });
  /*
  this.seat = file.find(obj => obj[key] === value);
  return this.seat;
  */
};
Seat.getSeatByNumber = function(seatNumber, result, next) {
  try {
    this.seat = this.findSeat("seatNumber", seatNumber)
      .then(seat => {
        if (seat !== undefined && Object.keys(seat).length > 0) {
          result(null, seat);
        } else {
          result({ error: true, message: "Seat not found" });
        }
      })
      .catch(error => {
        return;
      });
  } catch (error) {
    console.log(error);
  }
  /*  if (this.seat !== undefined && Object.keys(this.seat).length > 0) {
    result(null, this.seat);
  } else {
    result({ error: true, message: "Seat not found" });
  }*/
};

我尝试遵循一些在线指南,但似乎无法将错误响应重新表达出来。 /* ... */中的代码是我尝试转换的原始代码

更新

第一抓和第二抓之间有什么区别。还有为什么我的app.js无法捕获我返回的状态代码?

Seat.findSeat = function(key, value) {
  return new Promise((resolve, reject) => {
    const seat = file.find(r => r[key] === value);
    if (!seat) {
      reject({
        error: true,
        message: "Seat not found",
        status: 404
      });
    }
    resolve(seat);
  });

};

Seat.getSeatByNumber = function(seatNumber, result, next) {
  try {
    this.seat = this.findSeat("seatNumber", seatNumber)
      .then(seat => {
        console.log(seat);
        if (seat !== undefined && Object.keys(seat).length > 0) {
          result(null, seat);
        } else {
          result({ error: true, message: "Seat not found" });
        }
      })
      .catch(error => {
        console.log("1st catch");
        return result(error);
      });
  } catch (error) {
    console.log("outer catch");
    console.log(error);
    result(error);
  }

};

app.js 错误不会在此处记录

app.use(function(err, req, res, next) {
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};
  console.log('apperro' , err) // <-- does not log this
  res.status(err.status || 500);
  res.json({ error: err.message });
});

更新2

添加next后的

给我以下错误。您可以将seatData/1T传递到沙箱https://codesandbox.io/s/elucidate-api-fokd8中的网址中

(node:319) UnhandledPromiseRejectionWarning: TypeError: next is not a function
    at Seat.getSeatByNumber (/sandbox/src/controller/appController.js:15:14)
    at findSeat.then.catch.error (/sandbox/src/model/seat.js:45:16)
(node:319) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:319) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

1 个答案:

答案 0 :(得分:1)

您似乎想要的是,一旦错误从模型文件中消失,就将错误带回控制器?

似乎您没有在模型文件的2个catch块中返回错误。

在您的catch块中,您应该使用return对象,而不是console.log(error)result,就像这样:result(error);

更新:

在您的控制器中,您正在使用res.json()。为了让您的逻辑处理进入app.use中定义的下一步,您可以尝试使用带有相关参数的next()而不是res.json()

使用res.json(),请求仅发送JSON响应并在此结束。

更新2:

exports.fetch_seat = (req, res, next) => {
  Seat.getSeatByNumber(req.params.seatNumber, (err, seat) => {
    if (err) next(err); // Error, pass error back to express
    else res.json(seat); // No error, respond immediately
  });
};