javascript Javascript函数不返回值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9384580/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 06:29:55  来源:igfitidea点击:

Javascript function not returning value

javascriptjquerycoldfusion

提问by Michael BW

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). Even if it gets an error, I would think I have accounted enough for that to at least get a return value.

查询成功运行,但 js 函数不返回值(显示为未定义)。即使出现错误,我认为我已经考虑到了至少可以获得一个返回值。

Ideas?

想法?

回答by Ben Lee

The function is not returning a value because the returns in your method are embedded inside callback functions. They are only returning from those callbacks, not from your main function. Consider, for example, your "success" callback:

该函数没有返回值,因为return方法中的s 嵌入在回调函数中。它们仅从这些回调中返回,而不是从您的主函数中返回。例如,考虑您的“成功”回调:

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

This returnis just returning from the successfunction... It doesn't bubble up to your updateStringCallfunction.

return只是从success函数返回...它不会冒泡到您的updateStringCall函数中。

The reason it has to work this way is because ajax calls are asynchronous. Your method returns immediatelywhile 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 调用是异步的。当请求在后台发生时,您的方法会立即返回。因此,为了获得返回值,您必须传入一个在准备好时可以访问该值的回调,然后从 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 alreadyhas 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 中一种非常常见的结构。

回答by Jordan

Ajax calls are asynchronous. You'll have to work with your result from within the success callback of the $.ajax().

Ajax 调用是异步的。您必须在 $.ajax() 的成功回调中处理您的结果。