[RN] Add a timeout for loading the configuration

This commit is contained in:
Lyubo Marinov
2017-12-05 14:34:24 -06:00
parent 38b645bc27
commit a5538adf8a
7 changed files with 84 additions and 44 deletions

View File

@@ -1,3 +1,7 @@
// @flow
import { timeoutPromise } from './timeoutPromise';
/**
* Loads a script from a specific URL. React Native cannot load a JS
* file/resource/URL via a <script> HTML element, so the implementation
@@ -6,9 +10,12 @@
*
* @param {string} url - The absolute URL from which the script is to be
* (down)loaded.
* @param {number} [timeout] - The timeout in millisecnods after which the
* loading of the specified {@code url} is to be aborted/rejected (if not
* settled yet).
* @returns {void}
*/
export function loadScript(url) {
export function loadScript(url: string, timeout: ?number): Promise<void> {
return new Promise((resolve, reject) => {
// XXX The implementation of fetch on Android will throw an Exception on
// the Java side which will break the app if the URL is invalid (which
@@ -26,7 +33,31 @@ export function loadScript(url) {
return;
}
fetch(url, { method: 'GET' })
let fetch_ = fetch(url, { method: 'GET' });
// The implementation of fetch provided by react-native is based on
// XMLHttpRequest. Which defines timeout as an unsigned long with
// default value 0, which means there is no timeout.
if (timeout) {
// FIXME I don't like the approach with timeoutPromise because:
//
// * It merely abandons the underlying XHR and, consequently, opens
// us to potential issues with NetworkActivityIndicator which
// tracks XHRs.
//
// * @paweldomas also reported that timeouts seem to be respected by
// the XHR implementation on iOS. Given that we have
// implementation of loadScript based on fetch and XHR (in an
// earlier revision), I don't see why we're not using an XHR
// directly on iOS.
//
// * The approach of timeoutPromise I found on the Internet is to
// directly use XHR instead of fetch and abort the XHR on timeout.
// Which may deal with the NetworkActivityIndicator at least.
fetch_ = timeoutPromise(fetch_, timeout);
}
fetch_
.then(response => {
switch (response.status) {
case 200: