本文介绍了发送标头后无法删除标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从服务器获得不一致的结果.有时会发送正确的响应,有时会出现错误

I am getting inconsistent results from my server. Sometimes the right response is sent and sometimes I get the error

使用Node.js,Koa.js和Mongoose

Using Node.js, Koa.js, and Mongoose

router
.get('/events/', function* getEvent() {
  let eventList = [];
  yield Event.find({}, (error, events) => {
    if (error) {
      this.response.body = 'Unable to get events.';
      this.status = 404;
      return;
    }

    eventList = events;
    eventList.sort((first, second) => {
      // sort implementation
    });

    this.response.body = eventList;
    this.status = 200;
  });
});

推荐答案

问题是由您的回调引起的,该回调引入了竞争条件,因为您的收益没有等待其完成.在Koa v1.x中,通常只使用回调API来返回诺言.

The issue is caused by your callback which introduces a race condition since your yield isn't waiting for it to finish. In Koa v1.x, you generally only use a callback API to return a promise.

以下是您使用Koa v1.x编写示例的方法:

Here's how you'd write your example with Koa v1.x:

router
  .get('/events', function * () {
    let events
    try {
      events = yield Event.find({})
    } catch (err) {
      this.status = 503
      this.body = 'Unable to get events'
      return
    }
    events = sort(events)
    this.body = events  // Implicit 200 response
  })

Event.find只需要返回可承诺的东西.检查您使用的库是否有一个可返回承诺的版本.

Event.find just needs to return something yieldable like a promise. Check to see if the library your using has a promise-returning version.

尽管通常您会这样写:

router
  .get('/events', function * () {
    let events = yield Event.find({})
    events = sort(events)
    this.body = events
  })

由于如果Event.find关闭,这是内部错误(500响应). Koa会将未捕获的错误转化为500个响应.

Since it's an internal error (500 response) if Event.find is down. Koa will turn uncaught errors into 500 responses.

这篇关于发送标头后无法删除标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-27 04:46