如何在前一个承诺解决后执行承诺?

时间:2021-04-15 23:04:44

I need to do 2 http requests on angularjs, but I need that the second request only be executed after the first request has been resolved. Because -> And I need of the return of the two requests at the same time. Which is the best way to do this?

我需要在angularjs上做2个http请求,但是我需要第二个请求只在第一个请求被解析后执行。因为 - >我需要同时返回两个请求。这是最好的方法吗?

I do an test, with the code below, however the two promises are executed at the same time. How can I do for that the second promise only be executed after the first promise has been resolved?

我使用下面的代码进行测试,但是两个promise同时执行。我怎么能这样做,第二个承诺只在第一个承诺解决后执行?

$q.all([
    getData(api_url('categories')),
    getData(api_url('tags')), // This promise must only be executed after the promise above has been resolved

]).then(function (response) {
    $scope.categories = response[0];
    $scope.tags = response[1];

}).catch(function (error) {
    notify('Cannot get data for articles register!', 'error');
});

[UPDATE] I have managed to solve the problem with this code, but it does not seem to me the best way to do this. How can I improve this code?

[更新]我已经设法解决了这个代码的问题,但在我看来这不是最好的方法。我该如何改进这段代码?

getData(api_url('categories')).then(function (response) {
    categories = response.data;

    return getData(api_url('tags')).then(function (response) {
        tags = response.data;

        $scope.categories = categories;
        $scope.tags = tags;
    });

}).catch(function (response) {
    notify('Cannot get data for articles register!', 'error');
});

[SOLUTION]

[解]

var categoriesPromise = getData(api_url('categories'));

var tagsPromise = categoriesPromise.then(function (response) {
    return getData(api_url('tags'));
});

$q.all([categoriesPromise, tagsPromise]).then(function (response) {
    $scope.categories = response[0].data;
    $scope.tags = response[1].data;
}).catch(function (response) {
    notify('Cannot get data for articles register!', 'error')
});

1 个解决方案

#1


0  

this might be a bit nicer?

这可能会更好一点?

getData(api_url('categories'))
  .then(function(response) {
    $scope.categories = response.data;

    return getData(api_url('tags'));
  }).then(function(response) {
    $scope.tags = response.data;
  }).catch(function(response) {
    notify('Cannot get data for articles register!', 'error');
  });

#1


0  

this might be a bit nicer?

这可能会更好一点?

getData(api_url('categories'))
  .then(function(response) {
    $scope.categories = response.data;

    return getData(api_url('tags'));
  }).then(function(response) {
    $scope.tags = response.data;
  }).catch(function(response) {
    notify('Cannot get data for articles register!', 'error');
  });