2016-12-08 70 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