2016-12-08 66 views
0

第一个$ http.post承诺(当与.then一起使用时)返回一个对象没有问题,但是当我嵌套另一个$ http.post承诺时(也可以使用。然后)我永远不会得到一个对象返回。无论我做什么,它总会回报一个承诺。

function getDocumentPages($http) { 
var data = { fileName: '@fileNameUrlSafe' }; 
return $http.post(controllerBaseUrl + "GetDocumentPages", data) 
.then(function successCallback(response) { 
    // ======================================= 
    // THE LINE BELOW ALWAYS RETURNS A PROMISE 
    // ======================================= 
    var fieldPages = getDocumentFormFields($http); 
    var tempModel = { 
     pages: response.data, 
     fieldPages: fieldPages 
    }; 
    return tempModel; 
    }, function errorCallback(response) { 
    console.log(response); 
}); 
} 

function getDocumentFormFields($http) { 
var data = { fileName: '@fileNameUrlSafe' } 
return $http.post(controllerBaseUrl + "GetDocumentFormFields", data) 
.then(function successCallback(response) { 
    return response.data; 
}, function errorCallback(response) { 
    console.log(response); 
}); 
} 
+0

在控制台中的任何错误? –

+0

没有没有错误 – RichC

回答

1
function getDocumentPages($http) { 
var data = { fileName: '@fileNameUrlSafe' }; 
return $http.post(controllerBaseUrl + "GetDocumentPages", data) 
    .then(function successCallback(response) { 

     // ======================================= 
     // THE LINE BELOW ALWAYS RETURNS A PROMISE 
     // ======================================= 
     return getDocumentFormFields($http).then(function(fieldPages) { 
      var tempModel = { 
      pages: response.data, 
      fieldPages: fieldPages 
      }; 
      return tempModel; 
     }); 

    }, function errorCallback(response) { 
     console.log(response); 
    }); 
} 

使用这样的:

getDocumentPages($http).then(function(response) { 
    //Do something with the response 
    console.log(response); 
}); 

这应该工作!

+0

是的 - 那是固定的。为什么我不能像我正在尝试做的那样做这件事有什么原因吗?似乎不合逻辑。 – RichC

+1

getDocumentFormFields()进行异步调用,然后立即返回承诺;它不会等待解决的承诺,然后在返回之前运行该块!将* then *添加到函数调用中可确保在您的代码依赖于响应运行之前解决了承诺。 – sledsworth