我是 Stack Overflow 的新手,所以我希望我能找到能够解决我的问题的人。
正在发生的事情:我目前正在使用 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 请求。
如果我不清楚,请告诉我,谢谢您的帮助!
您需要收集Promise
Array 中的所有对象,然后使用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]);
}
}
}
});
注意:我没有测试上面的代码,所以可能会有一些错误。我希望它会帮助你。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句