简体   繁体   中英

RSVP - Handling timeouts with promises

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.

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.

/**
 * @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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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