为什么嵌套的promise不适用于我的代码

时间:2015-09-25 05:03:53

标签: angularjs asynchronous angular-promise

在此之前我从未尝试过嵌套的承诺。然而,我的所有逻辑和互联网都说他们应该工作。但是在我的代码下面,这并没有发生:

APIService.getData(Config + headerURL).then(function (response) {
            console.log(headerURL);
            console.log("header response from API", response);

            //Calling API for reference data
            $http.get(DataURL).then(function (refData) {
                console.log(Config + LeverReferenceDataURL);
                $scope.levers = refData;
                console.log("Setting ReferenceDataURL response from API", $scope.levers);


            },function (error) {
                console.log("API call for Reference data failed");
            });

        },function(error) {
            console.log("API call for header data failed");
        });

这里我试图进行两次API调用以从两个URl接收数据。 APIService是我用来进行http调用的Angular服务。在此代码之前,我使用相同的服务进行两个调用。然后我认为无法使用相同的延迟对象解析两个API调用。所以现在我正在使用$ http直接尝试内部调用。

我想要的是第二次调用应该在第一次之后立即进行,我的所有代码(在上面一段代码之下)应该等到成功解决或拒绝这两个(或其中一个)调用。

目前我的代码失败了,因为在第二个呼叫数据到达之前,所有代码都依赖于该数据运行而第二个呼叫的结果稍后到达。

我错了。什么是实现我想要的结果的正确方法?

2 个答案:

答案 0 :(得分:0)

除非您的第二个API调用依赖于第一个API调用返回的数据,否则嵌套只会使您的代码更难理解。你可以尝试这样的事情。

var firstPromise = APIService.getData(Config + headerURL);
var secondPromise = firstPromise.then(function() {
  return $http.get(DataURL);
});

$q.all([firstPromise, secondPromise]).then(function(responses) {
  var firstData = responses[0];
  var secondData = responses[1];

  /* Code here will not execute until both API 
     calls were successfully made */

}).catch(function(error) {
  console.log("API call failed", error);
});

通过在第一个承诺之后用then定义第二个承诺,它保证第二个API调用仅在第一个成功之后才会发生。此外,您需要为此解决方案注入$q

答案 1 :(得分:-1)

这是以plunker http://plnkr.co/edit/wvjdpe

形式的示例
// Service
return {
    getData: function(url) {
        return $http.get(url);
    }
}

// Controller
service.getData(someUrl).then(function(someData) {
    service.getData(otherUrl).then(function(otherData) {
        // blabla
    })    
})

您需要返回承诺才能将它们链接起来。