Как ждать завершения http-запроса?Javascript - PullRequest
1 голос
/ 15 марта 2019

Я новичок в переполнении стека, поэтому надеюсь, что найду того, кто сможет решить мою проблему.

Вот что происходит: я сейчас создаю приложение с ionic, и мне нужно выполнить несколько HTTP-запросов, потому что мне нужны данные из GoogleMaps. До этого я работал с очень немногими путевыми точками, поэтому мог выполнять только один запрос, но сейчас, и поскольку мы ограничены, мне нужно выполнить многие из них.

Проблема в том, что я пытаюсь заполнить матрицу расстояниями между местами, но javascript у меня асинхронный, и, таким образом, он не работает ... Вот фрагмент моего кода, только для вашего понимания, я пытаюсь создать цикл for, чтобы заполнить мою матрицу, и я хотел бы найти способ заставить мой скрипт ждать ответа на каждый запрос для продолжения.

for ( this.k = 0; this.k < this.adresses_split.length - 1; this.k ++){
        this.url = this.url1 + this.adresses_split[this.k] + this.url2 + this.phraseCl  + this.url3
        console.log(this.url)
          
        this.httpB.get(this.url,{},{}).then(data =>{
        
          for ( this.i = 1; this.i < 4; this.i++ ){
            
            
            for(this.j = this.i + 1 + 3*this.k ; this.j< this.clients.length + 1; this.j++ ){
              this.distances.push(this.i- 1 + 3*this.k);
              this.distances.push(this.j - 1);
              this.distances.push(data.data.split('elements')[this.i].split('duration')[this.j].split('value" : ')[1].split(' ')[0])
              
            }
            
          } 

          
        }).catch(error => {
          console.log(error.status);
          this.teste=error.error; // error message as string
          console.log(error.headers);
          
        });

      }

httpB означает HTTP Bis, потому что я создал другой, но это простой http-запрос.

Если мне не ясно, просто скажите мне, спасибо за вашу помощь!

1 Ответ

0 голосов
/ 15 марта 2019

Вам нужно собрать все Promise объекты в массиве, а затем использовать Promise.all(theCollection).then(()=>{}).

Вы не разместили здесь весь свой код ... поэтому я угадаю некоторые догадки.Следующий код даст вам некоторое представление о том, как решить проблему.

var promises = [];
for (this.k = 0; this.k < this.adresses_split.length - 1; this.k ++){
    this.url = this.url1 + this.adresses_split[this.k] + this.url2 + this.phraseCl  + this.url3
    console.log(this.url)

    promises.push(
        this.httpB.get(this.url,{},{}).then(data =>{
            for ( this.i = 1; this.i < 4; this.i++ ){
                for(this.j = this.i + 1 + 3*this.k ; this.j< this.clients.length + 1; this.j++ ){
                    this.distances.push(this.i- 1 + 3*this.k);
                    this.distances.push(this.j - 1);
                    this.distances.push(data.data.split('elements')[this.i].split('duration')[this.j].split('value" : ')[1].split(' ')[0]);
                }
            } 
        }).catch(error => {
              console.log(error.status);
              this.teste=error.error; // error message as string
              console.log(error.headers);
        })
    );

}

Promise.all(promises).then(() => {
    ... do you stuff...
}

Обновление: В ответ на ваш комментарий - если вам нравится просматривать и / или обрабатывать результатывсе запросы get за один раз, измените код следующим образом:

var promises = [];
for (this.k = 0; this.k < this.adresses_split.length - 1; this.k ++){
    this.url = this.url1 + this.adresses_split[this.k] + this.url2 + this.phraseCl  + this.url3
    console.log(this.url)
    promises.push(this.httpB.get(this.url,{},{})
        .then(data => data)
        .catch(error => {
              console.log(error.status);
              this.teste=error.error; // error message as string
              console.log(error.headers);
        })
    );    
}

Promise.all(promises).then(results => {
    for(let r = 0; r < results.length; r++){
        let data = results[r];

        for(this.i=1; this.i < 4; this.i++){
            for(this.j = this.i + 1 + 3*this.k ; this.j< this.clients.length + 1; this.j++ ){
                this.distances.push(this.i- 1 + 3*this.k);
                this.distances.push(this.j - 1);
                this.distances.push(data.data.split('elements')[this.i].split('duration')[this.j].split('value" : ')[1].split(' ')[0]);
            }
        }
    }
});

Примечание: Я не тестировал приведенный выше код, поэтому могут быть некоторые ошибки.Я надеюсь, что это поможет вам.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...