74dbc71c84
You can potentially close an EventSource before its first tick by immediately setting the readyState to a non-open state. Therefore it never opens. Calling `open` will then open it. 'Open' fits better than 'reopen' when taking the above into account
30 lines
917 B
JavaScript
30 lines
917 B
JavaScript
export default function(P = Promise) {
|
|
return function(source, listeners) {
|
|
let current;
|
|
if (typeof source.getCurrentEvent === 'function') {
|
|
current = source.getCurrentEvent();
|
|
}
|
|
if (current != null) {
|
|
// immediately resolve if we have previous cached data
|
|
return P.resolve(current.data).then(function(cached) {
|
|
source.open();
|
|
return cached;
|
|
});
|
|
}
|
|
// if we have no previously cached data, listen for the first response
|
|
return new P(function(resolve, reject) {
|
|
// close, cleanup and reject if we get an error
|
|
listeners.add(source, 'error', function(e) {
|
|
listeners.remove();
|
|
e.target.close();
|
|
reject(e.error);
|
|
});
|
|
// ...or cleanup and respond with the first lot of data
|
|
listeners.add(source, 'message', function(e) {
|
|
listeners.remove();
|
|
resolve(e.data);
|
|
});
|
|
});
|
|
};
|
|
}
|