如何通过 `$resource` 中的 return 获取 `$promise.then` 的值?

How to get `$promise.then` value by return in the `$resource`?

来自其中一个服务,我是retuning一个后端输出。我正在获取值,但是如何从返回的对象中获取结果值?

这是我的代码:

var queryConractorInfo = function ( server, contractorParams ) {

            return server.contractorInfo.get(contractorParams)
                  .$promise.then(function ( contractorInfo ) {

                    return contractorInfo;

            })

}

这是我的电话:

console.log( queryConractorInfo( server, contractorParams) );

这是我得到的输出:

{
  "$$state": {
    "status": 1,
    "value": { // i want to get this from returned object.
      "ActualPercentage": "33.5",
      "AllWeeks": [
        "/Date(1446930000000+0300)/",
        "/Date(1446498000000+0300)/",
        "/Date(1439154000000+0300)/",
        "/Date(1438635600000+0300)/",
        "/Date(1436043600000+0300)/",
        "/Date(1431550800000+0300)/",
        "/Date(1389733200000+0300)/",
        "/Date(1332277200000+0300)/"
      ]
}
}
}

我这样试过:

var queryConractorInfo = function ( server, contractorParams ) {

            return server.contractorInfo.get(contractorParams)
                  .$promise.then(function ( contractorInfo ) {

                    return contractorInfo.promise;
                    //adding promise but not working

            })

}

有点不清楚您要实现的目标,但这应该对您有所帮助。 我想你想从你得到的函数中 return JSON 对象?

假设您将函数调用为

myFuncToGetJSON().then(function(result){
    //result is the JSON object you are expecting
});

并且在您获得 JSON

的函数中
function myFuncToGetJSON(){
    var deferred = $.Deferred(); // create a deferred object
    //do steps to generate JSON
    deferred.resolve(theJSONYouHaveGenerated);
    return deferred.promise();
}

更多帮助HERE

据我了解你的情况,你似乎坚持要退货。

这不是它处理 promise 的方式。从 promise 回调(或 resolve 函数)返回只会将数据传递给下一个 .then() 函数。您可以链接许多 then-calls

var queryContractorInfo = function ( server, contractorParams ) {

    return server.contractorInfo.get(contractorParams)
        .$promise.then(function ( contractorInfo ) {

            // This will return to the next .then() call
            return contractorInfo;
        })
        .then(function(contractorInfo) {

            // Another then call, understand?
        });
}

基本上是这样的

// Outer variable, initialized to null (use an empty object if you prefer)
var queryContractorInfo = null;

server.contractorInfo.get(contractorParams)
    .$promise.then(function ( contractorInfo ) {

        // Now I can set queryContractorInfo
        queryContractorInfo = contractorInfo;

        // You can return, but you don't need to, if this is the final then
    });

queryContractorInfo 为空,只要查询正在进行。当你得到一个结果时,变量被设置为结果数据。在 then 函数中,如果您想使用此变量,您现在可以触发更多函数。