-
-
Save isnifer/d55b9c26f286a96a0cc3d80e90f6d2d8 to your computer and use it in GitHub Desktop.
Long Polling in React Native
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*--- LONG POLL --*/ | |
/** | |
* Adapted from http://blog.gospodarets.com/fetch_in_action/ | |
* many thanks! | |
*/ | |
var MAX_WAITING_TIME = 5000;// in ms | |
var getJSON = function (params) { | |
var wrappedPromise = {}; | |
var promise = new Promise(function (resolve, reject) { | |
wrappedPromise.resolve = resolve; | |
wrappedPromise.reject = reject; | |
}); | |
wrappedPromise.then = promise.then.bind(promise); | |
wrappedPromise.catch = promise.catch.bind(promise); | |
wrappedPromise.promise = promise;// e.g. if you want to provide somewhere only promise, without .resolve/.reject/.catch methods | |
fetch(params.url, { | |
method: 'GET', | |
headers: { | |
'Accept': 'application/json' | |
} | |
}) | |
.then(function (response) { | |
wrappedPromise.resolve(response); | |
}, function (error) { | |
wrappedPromise.reject(error); | |
}) | |
.catch(function (error) { | |
wrappedPromise.catch(error); | |
}); | |
var timeoutId = setTimeout(function () { | |
// reject on timeout | |
wrappedPromise.reject(new Error('Load timeout for resource: ' + params.url)); | |
}, MAX_WAITING_TIME); | |
return wrappedPromise.promise | |
.then(function(response) { | |
clearTimeout(timeoutId); | |
return response; | |
}) | |
.then(function(response) { | |
if (response.status === 200 || response.status === 0) { | |
return Promise.resolve(response) | |
} else { | |
return Promise.reject(new Error(response.statusText)) | |
} | |
}) | |
.then(function(response) { | |
return response.json(); | |
}); | |
}; | |
(function poll() { | |
getJSON({ | |
url: 'api.example.com/poll' | |
}).then(function(data) {// on success | |
poll(); | |
console.log('JSON parsed successfully!'); | |
console.log(data); | |
}, function(error) {// on reject | |
poll(); | |
console.error('An error occured!'); | |
console.error(error.message ? error.message : error); | |
}); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment