javascript - Http get 调用返回太多结果。::JavaScript

标签 javascript http asynchronous

我有一个函数:

private getValues() {
  this._values = [];
  this._watchlistElements.map(v =>
    this.http.get('http://localhost/getValue/' + v.xid)
      .subscribe(res => {
        this._values.push(res.json());
       console.log(this._values.length);
  }))
};

调用该函数后,我得到的结果如下所示:

enter image description here

我的问题是如何检查_values 变量的实际长度?该解决方案有效,但如您所见,它会在每次迭代时返回一个结果,就像在循环中一样。如何让它只返回一个最终结果?在这种情况下,--> 的长度应该只是 7

最佳答案

在 Promise 中捕获每个调用,然后等待所有调用是一个好方法:

Promise.all(this._watchlistElements
  .map(v => new Promise(resolve => this.http.get(...).subscribe(res => resolve(res.json())))))
    .then(arrayWithResultFromEachCall => console.log(arrayWithResultFromEachCall.length))

关于javascript - Http get 调用返回太多结果。::JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41199265/

相关文章:

javascript - 在 Angular 2 模板上绑定(bind) HTML 代码字符串

javascript - global.process 的构造函数是否存储在除 global.process.constructor 之外的任何位置?

javascript - 基于带有句点的值的 jQuery 属性选择器

entity-framework - Entity Framework 6 中的多异步?

javascript - 在 Javascript 中停止异步进程的最佳方法

Javascript:如何编写将异步执行的函数?

javascript - 为什么 jQuery 中的 "this"参数返回带有 anchor 的 href

perl - WWW::Curl 无法在 POST 正文中附加 WWW::Curl::Form 数据

json - Angular 如何检查 HttpRequest 对象以为 header 设置正确的内容类型?

ajax - 混合内容 : Call http content from API from https page