从异步回调函数返回结果

时间:2015-06-27 23:58:32

标签: javascript function asynchronous return-value asynccallback

我在stackoverflow上看到很多关于在回调函数中获取异步调用的返回值的帖子,但是我想知道我是否可以在回调内部得到结果。

对于Eg: 当前情景

    <!--Inline Task for getting the Current Month and Year by executing a C# code inside this MSBUILD task-->
   <UsingTask TaskName="GetCurrentMonthYear" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll" >

  <ParameterGroup>
    <CurrentMonth ParameterType="System.String" Output="true" />
    <CurrentYear ParameterType="System.Int32" Output="true" />
  </ParameterGroup>

    <Task>
      <Using Namespace="System.Globalization" />
      <Code Type="Fragment" Language="cs">
      CurrentMonth = DateTime.Now.ToString("MMMM", CultureInfo.CurrentCulture);
      CurrentYear = DateTime.Now.Year;
    </Code>
  </Task>

</UsingTask>

  <!--Calling this target before Compile target to set the appropriate properties-->
  <Target Name="SetCurrentMonthYear" BeforeTargets="Compile">

  <GetCurrentMonthYear>
    <Output PropertyName="CurrentMonth" TaskParameter="CurrentMonth" />
    <Output PropertyName="CurrentYear" TaskParameter="CurrentYear" />
  </GetCurrentMonthYear>

  <PropertyGroup>
    <DefineConstants>$(DefineConstants);CurrentMonth=$(CurrentMonth)</DefineConstants>
    <DefineConstants>$(DefineConstants);CurrentYear=$(CurrentYear)</DefineConstants>
  </PropertyGroup>

</Target>

我想拥有什么

myFunc(arg1,arg2, mycallback);
..
function mycallback(values)
{
//Process values
alert(values);
}

上述情况是否可行?请告诉我。

干杯。

2 个答案:

答案 0 :(得分:0)

你不能那样做,你能做的就是利用Promises

引用: ...我可以在回调内部得到结果。

如果您担心callback hell,那么您可以通过使用承诺缓解这一点:

来自bluebird library的示例:

你应该使用promises来解决这个问题:

fs.readFile("file.json", function(err, val) {
    if( err ) {
        console.error("unable to read file");
    }
    else {
        try {
            val = JSON.parse(val);
            console.log(val.success);
        }
        catch( e ) {
            console.error("invalid json in file");
        }
    }
});

Into this:

    fs.readFileAsync("file.json").then(JSON.parse).then(function(val) {
        console.log(val.success);
    })
    .catch(SyntaxError, function(e) {
        console.error("invalid json in file");
    })
    .catch(function(e) {
        console.error("unable to read file")
    });

答案 1 :(得分:0)

您可以使用promise库。 这是使用jQuery promise

的实现
(function ($) {
    function myFunc(arg1,arg2){
          var defer = $.Deferred(),
              result=arg1+arg2; 
          defer.resolve(result);
          return defer.promise();
    }

    myFunc(1,2).then(function(result){
        console.log('result is: '+result)
        //manipulate result as you want
        result=result+1;
        showFinalResult(result);
    });
    function showFinalResult(result){
        alert(result);
    }
})(jQuery);

http://jsfiddle.net/gfmvgc8p/

相关问题