$ q.allPromises返回一个数组,但我只想要一个元素,而不是全部

时间:2017-01-31 16:13:32

标签: javascript angularjs node.js angular-promise

我正在使用

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

它是第一次工作,但我在24小时后调用这个方法并找到"数据"是一个对象数组,每当我用新的http json对象调用$ q.allPromises时它就会被追加。

我怎么能忘记旧的"对象"在数组中。我每24小时拉一个json,只关心我刚刚取下的json对象。我想忽略从之前的http promise请求中删除的json对象,但它似乎不断附加到数组

我尝试添加

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

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

1 个答案:

答案 0 :(得分:3)

您不需要使用$q.all$http提供程序单独返回一个promise:

$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是一种在执行操作之前等待许多承诺解决的特殊方法,如下所示:

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
});