DART函数,嵌套/内部函数变量

时间:2014-08-19 18:17:03

标签: nested dart mailer nested-function

我将以下代码作为匿名函数(也是函数文字或lambda抽象),在DART mailer中使用

email(){ 
   ...
   emailTransport.send(envelope)
   .then((success) => print('Email sent! $success'))
   .catchError((e) => print('Error occured: $e'));
}

这很好用,但我需要更换" print"通过"返回"如下所示:

email(){ 
   ...
   emailTransport.send(envelope)
   .then((success) => return 'Email sent! $success')
   .catchError((e) => return 'Error occured: $e');
}

但失败了,回报没有得到承认!

我尝试了以下代码,但也失败了。

email(){ 
   ...
   var msg;
   ...
   emailTransport.send(envelope)
   .then((success) => msg = 'Email sent! $success')
   .catchError((e) => msg = 'Error occured: $e');

 return msg;
}

但" msg"保持不变!

任何想法。

1 个答案:

答案 0 :(得分:1)

这是因为函数中的return不是执行代码的Futures链的一部分。你的功能立即恢复;并且emailTransport.send方法还没有运行。

你的功能需要回归未来;我认为没有办法阻止"阻止"并等待结果(如果有的话,你可能不想这样做!)。

你可能想做这样的事情:

Future email() {
  ...
  return emailTransport.send(envelope)
   .then((success) => 'Email sent! $success')
   .catchError((e) => 'Error occured: $e');
}

然后,任何调用该函数的东西都需要链接到未来:

email()
  .then(msg => print(msg));

修改:根据评论

您调用的原始方法是异步的,因此返回Future(例如将来会完成的内容)。要使用此值执行任何操作,您需要" chain"更多代码到最后(因此,它也将返回Future,因为它无法运行直到第一个完成)。

您可以在链接函数内分配变量,例如

email().then((m) => msg = m);

但是,只有在异步操作完成后才会执行此操作,因此在此代码行之后它不会立即可用(这是原始代码示例中的错误)。如果你想对价值做点什么,你真的需要将它链接到未来:

email()
  .then(doSomeOtherThing)

doSomeOtherThing(String msg) {
  // Do more processing here
}

如果您对Futures不熟悉,Dart网站上的文章可能值得一读:Use Future-Based APIs

它非常类似于NodeJS的工作原理,不应该永远"阻止",而是需要在异步/长时间运行的工作之后完成的工作实际上是在回调中得到的标记到最后,运行时处于一个大循环中,处理队列中的下一个。这里有更多信息:The Event Loop and Dart

相关问题