A
A
Adel Khalitov2019-04-05 21:34:20
JavaScript
Adel Khalitov, 2019-04-05 21:34:20

How to achieve asynchrony?

There is a function:

getSome() {
   this.http.get('/some')
      .subscribe( (data: Array<object>)=> {
        console.log(data)
        this.AllMaterial = data; // не делает запрос
      }, err => {
        console.log(err)
      })
}

I have to call it after checking it in another function:
second() {
    if (this.isEmpty(this.AllMaterial)) {
      this.getSome();
    }
console.log(this.AllMaterial)
}

When called naturally in console:
undefined => console.log(this.AllMaterial)
somedate => console.log(data)
How to make this construction asynchronous?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vitaly Stolyarov, 2019-04-05
@SaveLolliPoP

async getSome() {
   const data = await this.http.get('/some').toPromise();
   
    console.log(data)
    
    return data;
}

async second() {
    if (this.isEmpty(this.AllMaterial)) {
      this.AllMaterial = await this.getSome()
    }
    console.log(this.AllMaterial)
}

A
Alex, 2019-04-05
@Kozack

Well, like this

getSome() {
   return this.http.get('/some')
}

second() {
    if (this.isEmpty(this.AllMaterial)) {
      this.getSome().subscribe( (data: Array<object>)=> {
        console.log(data)
        this.AllMaterial = data; // не делает запрос
        console.log(this.AllMaterial)
      }, err => {
        console.log(err)
      })
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question