vs_convoy
@vs_convoy

Как вернуть объект из callback'а?

К примеру делаю свою http библиотеку

Есть два файла:
easyhttp.js :
function easyHTTP() {
    this.http = new XMLHttpRequest();
}

//Making http GET request
easyHTTP.prototype.get = function(url, callback) {
    this.http.open('GET', url, true);

    let self = this; // this.http.status будет обращаться к самой себе, где нет http
    this.http.onload = function() { //можно пофиксить стрелочной функцией 
        if (self.http.status === 200) {
            callback(null, self.http.responseText);
        }
        else {
            callback('Error: ' + self.http.status);
        }
    }

    this.http.send();
}

и app.js:
const http = new easyHTTP;

//get posts
const posts = http.get('https://jsonplaceholder.typicode.com/posts', (err, response) => {
    if (err) {
        console.log(err)
    } else {
        return response;
    } 
});

posts равен undefined
Подскажите как мне вернуть self.http.status и присвоить в константу posts?
  • Вопрос задан
  • 143 просмотра
Пригласить эксперта
Ответы на вопрос 1
const http = new (function()
{

	this.get = function(url)
	{
		return new Promise((resolve, reject) =>
		{
			const query = new XMLHttpRequest();
			query.open('GET', url, true);

			query.onload = function() {
				if (query.status !== 200)
					return reject(new Error(`End by error ${query.status}`));

				return resolve(query.responseText);
			};

			query.send();
		});
	};

	return this;
});

const posts = http.get('https://jsonplaceholder.typicode.com/posts');

posts
.then(console.log)
.catch(console.log)
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы