简体   繁体   English

Javascript函数不返回值

[英]Javascript function not returning value

I am calling a function with the following code:我正在使用以下代码调用函数:

var resultz = nsEditor.updateStringCall(debtID, column2Change, value2Change, 4, 10);

The function that is being called but doesn't return a value被调用但不返回值的函数

        updateStringCall: function(pdebtID, pcolumn2Change, pvalue2Change, pmin, pmax){
try {
    var resultz2 = 0;
    $.ajax({
        type: "POST",
        url: "Components/MintLibraries.cfc",
        dataType: "json",
        cache: false,
        data: {
                method: 'StringUpdate',
            val2Change: pvalue2Change.trim(),
            debtID: pdebtID,
            column2Change: pcolumn2Change,
            greaterThan: pmin,
            lesserThan: pmax,
            returnFormat: "json"
        },
        success: function(response) {
                       resultz2 = 1;
          return resultz2;
        },  //end done
        error: function(jqXHR, textStatus, errorThrown){
           resultz2 = 0;
                       return resultz2;
                }); //end ajax call
} catch (e) {
    resultz2 = 0;
    return resultz2;
}  //end trycatch

}, // end updateStringCall }, // 结束updateStringCall

This function uses the .ajax to call a coldfusion cfc method StringUpdate:此函数使用 .ajax 调用 Coldfusion cfc 方法 StringUpdate:

<cffunction name="StringUpdate" access="remote" output="false" returntype="any" >    
     <cfargument name="val2Change" type="string"  required="true" />
     <cfargument name="debtID"  type="string"  required="true" />
     <cfargument name="column2Change"  type="string"  required="true" />
     <cfargument name="greaterThan"  type="numeric"   required="false" />
     <cfargument name="lesserThan"  type="numeric"  required="false" />
     <cfset var debt2Pass = int(val(arguments.debtID)) />
     <cfset var updQuery = "" />
     <cfset var retValue = 0 />
     <cfset var iVal = 0 /><cfset var valError = '' />
    <cftry>

        <cfquery name="updQuery" datasource="#application.datasource#" result="qResults"    >
                Update dmf set #arguments.column2Change# =
                 <cfqueryparam cfsqltype="cf_sql_varchar" value="#arguments.val2Change#"/>
                 where DebtID = 
                 <cfqueryparam cfsqltype="cf_sql_smallint" value="#arguments.debtID#"/>
        </cfquery> 
        <cfset retValue = 1 />    
     <cfcatch type="Any" >
                <cfset thrown = ThrowCFError(405,'debug',  'Error updating ' &  arguments.DebtID,arguments.val2Change & ', ' &  arguments.debtID & ',' & arguments.column2Change)  />
                  <cfset retValue = 0 />
         </cfcatch>
         </cftry>
    <cfreturn retValue />
</cffunction>

The query runs successfully but the js function doesn't return a value (it shows up as undefined).查询成功运行,但 js 函数不返回值(显示为未定义)。 Even if it gets an error, I would think I have accounted enough for that to at least get a return value.即使出现错误,我认为我已经考虑到了至少可以获得一个返回值。

Ideas?想法?

The function is not returning a value because the return s in your method are embedded inside callback functions. 该函数未返回值,因为方法中的return值嵌入在回调函数中。 They are only returning from those callbacks, not from your main function. 它们只是从那些回调中返回,而不是从主函数返回。 Consider, for example, your "success" callback: 例如,考虑一下你的“成功”回调:

success: function(response) {
    resultz2 = 1;
    return resultz2;
}

This return is just returning from the success function... It doesn't bubble up to your updateStringCall function. 这个return只是从success函数返回...它没有冒泡到你的updateStringCall函数。

The reason it has to work this way is because ajax calls are asynchronous. 它必须以这种方式工作的原因是因为ajax调用是异步的。 Your method returns immediately while the request happens in the background. 当请求在后台发生时,您的方法立即返回。 So in order to get the return value, you have to pass in a callback that has access to the value when it's ready, and then call the callback from within the ajax callbacks instead of returning a value. 因此,为了获得返回值,您必须传入一个在它准备就绪时可以访问该值的回调,然后从ajax回调中调用回调而不是返回值。

So change your method definition to this: 所以将方法定义更改为:

// Note I added a "callback" parameter
function(pdebtID, pcolumn2Change, pvalue2Change, pmin, pmax, callback) { ... }

And then in your ajax callbacks, call it instead of returning a value: 然后在你的ajax回调中,调用它而不是返回一个值:

success: function(response) {
    resultz2 = 1;
    callback(resultz2);
},
error: function(jqXHR, textStatus, errorThrown) {
    resultz2 = 0;
    callback(resultz2);
});

Finally, pass in a callback when you call this method: 最后,在调用此方法时传入回调:

nsEditor.updateStringCall(debtID, column2Change, value2Change, 4, 10, function(resultz) {
    // Do something with resultz
});

One final note, if you are going to have that blanket try/catch in there, you should change that to use the callback also: 最后要注意的是,如果要在那里进行毯子try / catch,你应该改变它以使用回调:

catch (e) {
    resultz2 = 0;
    callback(resultz2);
}

But really, I'd recommend just taking that try/catch out altogether. 但实际上,我建议完全接受尝试/捕获。 I can't see how that can possibly be helpful here. 我看不出这可能对你有什么帮助。 It will only hide actual problems with code that already has a better structure for error handling. 它只会隐藏已经具有更好的错误处理结构的代码的实际问题。 I suspect you just put in there to debug this return problem, but if it was there already, just take it out. 我怀疑你只是在那里调试这个返回问题,但如果已经存在,那就把它拿出去吧。

This is the world of event-driven functional programming! 这是事件驱动的函数式编程世界! It's a very common sort of structure in javascript. 这是javascript中一种非常常见的结构。

Ajax calls are asynchronous. Ajax调用是异步的。 You'll have to work with your result from within the success callback of the $.ajax(). 你必须在$ .ajax()的成功回调中使用你的结果。

add "async: false" like this:像这样添加“异步:假”:

type: "POST",
async: false,
url: "Components/MintLibraries.cfc",
dataType: "json",
cache: false,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM