RSVP - Handling timeouts with promises

a 夏天 提交于 2019-12-12 12:03:48

问题


I am using ember.js and 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.


回答1:


You can do that, but this should probably be handled by whatever is doing the async operation. If you're using jQuery ajax, then:

$.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.




回答2:


For an application that doesn't use jQuery, You may create an promise object that throws timeout error and run your tasks with Promise.race to get the first result.

/**
 * @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')
])


来源:https://stackoverflow.com/questions/22685055/rsvp-handling-timeouts-with-promises

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!