【问题标题】:$q.allPromises returns an array but I only want one element, and not all$q.allPromises 返回一个数组,但我只想要一个元素,而不是全部
【发布时间】:2017-02-01 01:10:13
【问题描述】:

我正在使用

$q.allPromises(http request).then (function (data) {
  //more code logic
})

它第一次工作,但我在 24 小时后调用此方法,发现“数据”是一个对象数组,每次我用新的 http json 对象调用 $q.allPromises 时都会附加它。

我怎样才能忘记数组中的旧“对象”。我每 24 小时拉一个 json 并且只关心我刚刚获取的 json 对象。我想忽略从上一个 http 承诺请求中拉下的 json 对象,但它似乎一直附加到一个数组中

我尝试添加

$q.allPromises(http request).then (function (data) {
  //more code logic
  data.shift ();
})

shift() 应该从数组中删除第一个元素,但它似乎不起作用。

【问题讨论】:

  • 当您显然只需要解决一个承诺时,使用 $q.all() 的目的是什么?你能提供代码示例吗?我假设您正在使用 AngularJS?
  • 是的,我正在使用 angularjs。我显然只需要解决一个承诺。我是 Angular 的新手,并在网上看到了一个关于如何使用 Promise 解析 http json 请求的示例,所以我逐字复制了它。我基本上是在调用解析 http req 以提取 json 并将某些值提取到变量名。
  • 今晚可以发代码了,可惜在家里
  • 当然。上传代码时告诉我。

标签: javascript angularjs node.js angular-promise


【解决方案1】:

您不需要使用$q.all$http 提供者自己返回一个承诺:

$http.get({...}).then(function(response) {
  console.log(response.data) // this will print actual data
});

$http.post({...}).then(function(response) {
  console.log(response.data) // this will print actual data
});

$q.all 是一种特殊的方法,用于在执行操作之前等待许多 Promise 解决,如下所示:

var promiseA = $http.get({...}).then(function(response) {
  console.log(response.data) // this will print actual data
});

var promiseB = $http.post({...}).then(function(response) {
  console.log(response.data) // this will print actual data
});

var arrayOfPromises = $q.all([promiseA, promiseB]).then(function(arrayOfResults) {
  console.log(arrayOfResults); // this will print an array of the results of the http requests
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-11
    • 2018-07-17
    • 2016-10-21
    • 2020-10-11
    • 1970-01-01
    • 2021-10-04
    • 1970-01-01
    • 2011-07-12
    相关资源
    最近更新 更多