Как работать с аснхронностью в пределах класса?



@Quintis

Что надо сделать что бы консоль логи выводили не null а количество полученных данных ?

class Test {
  constructor(){
    this.data = null;
  }
  method1 (){
    let xhr = new XMLHttpRequest();

xhr.open('GET', '/article/xmlhttprequest/example/load');

xhr.send();

xhr.onload = ()=> {
  if (xhr.status != 200) {
    alert(`Ошибка ${xhr.status}: ${xhr.statusText}`); // Например, 404: Not Found
  } else {
    console.log(`Готово, получили ${xhr.response.length} байт`); // response -- это ответ сервера
    this.data = xhr.response.length
  }
};

  }
  method2(){
    console.log(this.data + " method2 ")
  }
  method3(){
    console.log(this.data + " method3 ")
  }
}

const t = new Test()
t.method1()
//t.method2()
//t.method3()


Решения вопроса 1



@sergiks Куратор тега JavaScript

класс, не класс — тут не при чём. Надо разобраться с асинхронностью: коллбеками и промисами. Пришло время.

Примерно так можно

spoiler

class Test {
  constructor() {
    this.data = null;
  }

  method1() {
    return new Promise((resolve, reject) => {
      let xhr = new XMLHttpRequest();

      xhr.open('GET', '/article/xmlhttprequest/example/load');
      
      xhr.onload = () => {
        if (xhr.status != 200) {
          alert(`Ошибка ${xhr.status}: ${xhr.statusText}`);
          reject();  // облом!
        } else {
          console.log(`Готово, получили ${xhr.response.length} байт`);
          this.data = xhr.response.length
          resolve(); // выполнили обещание!
        }
      };

      xhr.send();
    })
  }

  method2() {
    console.log(this.data + " method2 ")
  }

  method3() {
    console.log(this.data + " method3 ")
  }
}

const t = new Test()
t.method1()
  .then(() => t.method2())
  .then(() => t.method3())

Или с этим же классом:

async function main() {
  const t = new Test();
  await t.method1();
  t.method2();
  t.method3();
}

main();



10

комментариев


Ответы на вопрос 0

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *