简体   繁体   English

RSVP - 使用承诺处理超时

[英]RSVP - Handling timeouts with promises

I am using ember.js and RSVP.我正在使用 ember.js 和 RSVP。

From what I can see, there is nothing that handles a timeout from an async call.据我所知,没有什么可以处理异步调用超时。

My thinking is to wrap the resolve handler using the decorator pattern to wrap the resolve handler in some code that will time the call and call reject if the timeout happens.我的想法是使用装饰器模式包装解析处理程序,将解析处理程序包装在一些代码中,这些代码将计时调用并在超时发生时调用拒绝。

Does this sound like a good idea or is there some built in support for timeouts that I have missed in RSVP.这听起来是个好主意还是我在 RSVP 中遗漏了一些对超时的内置支持。

For an application that doesn't use jQuery , You may create a promise object that throws timeout error and run your tasks with Promise.race to get the first result.对于不使用jQuery的应用程序,您可以创建一个抛出超时错误的承诺对象,并使用Promise.race运行您的任务以获得第一个结果。

/**
 * @param {number} msWait
 * @param {string} error - error message
 * @return {Promise}
 */
const promiseTimeout = (msWait, error) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => reject(new TimeoutError(error)), msWait)
  })
}

// Run tasks with timeout error
Promise.race([
  Android.detector(),
  IOS.detector(),
  promiseTimeout(settings.platformDetectionTimeout, 'Can\'t detect your platform')
])

You can do that, but this should probably be handled by whatever is doing the async operation.您可以这样做,但这可能应该由执行异步操作的任何人来处理。 If you're using jQuery ajax, then:如果您使用的是 jQuery ajax,则:

$.ajax({
  //...
  timeout: 1000 * 10 // 10 seconds
  //...
})

If you control the server side and expect congestion, then you should interrupt long running processes at that level and return an error.如果您控制服务器端并预期拥塞,那么您应该在该级别中断长时间运行的进程并返回错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM