Skip to content

Instantly share code, notes, and snippets.

@bakoushin
Last active April 11, 2018 08:19
Show Gist options
  • Save bakoushin/3ba2d4f35c0ecf7bd1ea0cc80c408015 to your computer and use it in GitHub Desktop.
Save bakoushin/3ba2d4f35c0ecf7bd1ea0cc80c408015 to your computer and use it in GitHub Desktop.
Request
'use strict';
class Request {
constructor() {
this._history = [];
this._promiseChain = Promise.resolve();
}
get(url, resolve, reject) {
this._promiseChain = this._promiseChain
.then(() => __fetch(url))
.then(response => {
this._history.push({
url,
error: false,
data: response
});
return resolve(response, this._history);
})
.catch(error => {
this._history.push({
url,
error: true,
data: error
});
return reject(error, this._history);
});
return this;
}
history(handler) {
this._promiseChain = this._promiseChain
.then(() => {
handler(this._history);
});
return this;
}
}
/*
/* Пример использования
*/
const request = new Request();
request
.get('https://yandex.ru', onResponse, onReject)
.get('https://github.com', onResponse, onReject)
.get('https://stackoverflow.com', onResponse, onReject)
.get('https://developer.mozilla.org', onResponse, onReject)
.get('https://css-tricks.com', onResponse, onReject)
.get('https://smashingmagazine.com', onResponse, onReject)
.get('https://alistapart.com', onResponse, onReject)
.get('https://javascript.ru', onResponse, onReject)
.get('https://codepen.com', onResponse, onReject)
.get('https://glitch.com', onResponse, onReject)
.get('https://behance.com', onResponse, onReject)
.get('https://dribbble.com', onResponse, onReject)
.get('https://travis-ci.org', onResponse, onReject)
.get('https://heroku.com', onResponse, onReject)
.get('https://ngrok.com', onResponse, onReject)
.history(printHistory);
function onResponse(response, history) {
console.log(response, getPreviousUrl(history));
}
function onReject(error, history) {
console.error(error.message, getPreviousUrl(history));
}
function getPreviousUrl(history) {
const previousRequest = history[history.length - 2];
if (!previousRequest) {
return 'Это первый запрос.';
}
const {url, error} = previousRequest;
return `Предыдущий url: ${url + (error ? ' (завершился с ошибкой)' : '')}`;
}
function printHistory(history) {
console.log('ИСТОРИЯ ЗАПРОСОВ:');
history.forEach(({url, error}, index) => {
console.log(`${index + 1}: ${url} ${error ? 'ОШИБКА' : 'OK'}`);
});
}
/** Эмулятор запроса к серверу.
* Возвращает Promise, резолвящийся в объект Response:
* {
* url: <string>,
* headers: {
* date: <date>
* }
* }
* Продолжительность запроса: случайное число в интервале от 0 до 1000 мс.
* Некоторые запросы случайным образом завершаются с ошибкой.
*/
function __fetch(requestUrl) {
class Response {
constructor(url) {
this.url = url;
this.headers = {
date: new Date()
};
}
}
function random(max) {
return Math.floor(Math.random() * max) + 1;
}
return new Promise((resolve, reject) => {
setTimeout(() => {
if (random(5) === 5) {
reject(new Error(`Запрос завершился с ошибкой: ${requestUrl}`));
} else {
resolve(new Response(requestUrl));
}
}, random(1000));
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment