2016-11-16 20 views
-2

我试图按照异步问题/指导这一页上,特别是如果你没有在你的代码使用jQuery是“答案,这个答案的函数这就是一个价值是你“这样一个问题:How do I return the response from an asynchronous call?但我似乎无法得到的值返回var返回从传入作为参数

function maxYvalue2(whendone) { 
    Rpt_scn_cost_v.find({ 
    filter: { 
     where: { 
     scenario_id: $stateParams.id 
     } 
    } 
    }).$promise.then(function(response) { 
    var maxYvalue = 0 
    for (i = 0; i < response.length; i++) { 
     currMaxYvalue = parseFloat(response[i].cur_cost) + parseFloat(response[i].tgt_cost); 
     if (currMaxYvalue > maxYvalue) { 
     maxYvalue = currMaxYvalue 
     }; 
    } 
    console.log("y3: " + maxYvalue) 
    whendone(maxYvalue); 
    return maxYvalue; 
    }); 
    return maxYvalue; 
}; 

function onComplete(maxYvalue1) { 

    mxVal = maxYvalue; 

    console.log("mx: " + mxVal) 

    return mxVal; 

}; 

var yVal = maxYvalue2(onComplete); 
console.log("fnc: " + yVal); 

yVal仍显示为不确定......我跟着前面的问题/答案,但仍无法在指南中得到的输出多数民众赞成....

我想跟随在代码中提到此结构:

function onComplete(a){ // When the code completes, do this 
    alert(a); 
} 

function getFive(whenDone){ 
    var a; 
    setTimeout(function(){ 
     a=5; 
     whenDone(a); 
    },10); 
} 

,然后调用它像这样:

getFive(onComplete); 

我是否在参考问题中回答了正确的部分?

+0

你确定你已经经历了你提到的问题吗?这是一个很长的答案,解释了这里的一切。 PS:作为一个侧面建议 - 学习如何缩进,目前几乎不可能在代码中看到层次结构。 – zerkms

+0

是的......我特别关注“如果你没有在代码中使用jQuery,这个答案是给你的”回应......我似乎无法弄清楚什么是错的......请注意,我'在JavaScript的一个n00b,所以我试图学习,因为我去... – user2061886

+0

不知道你为什么提到jquery,请重新阅读检查的答案。完全。 – zerkms

回答

2

承诺不使代码同步。你将永远无法立即从maxYvalue2返回值。只需返回诺言:

function maxYvalue2() { 
    return Rpt_scn_cost_v.find({filter: { where: {scenario_id: $stateParams.id}}}).$promise.then(function(response){ 
     var maxYvalue = 0 
     for (var i=0;i<response.length;i++) { 
      var currMaxYvalue = parseFloat(response[i].cur_cost) + parseFloat(response[i].tgt_cost); 
      if (currMaxYvalue > maxYvalue) { 
       maxYvalue = currMaxYvalue 
      }; 
     } 
     console.log("y3: " + maxYvalue) 
     return maxYvalue; 
    }); 
} 

maxYvalue2().then(function onComplete(yVal) { 
    console.log("fnc: " + yVal); 
});