同步返回值并在dart中等待 [英] returning a value in sync and await in dart

查看:212
本文介绍了同步返回值并在dart中等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解Dart中async和await的用法。不知何故,我在某些方法中无法返回值。

I am trying to understand the usage of async and await in Dart. Somehow I am having issues returning values in certain methods.

请考虑以下代码

Future<int> getMrn() async {
  var mrnRef = await firebaseClient.child('mrn');

  DataSnapshot ss;
  StreamSubscription<Event> onValueSubscription = await mrnRef.onValue
      .listen((event) {
    ss = event.snapshot;

    return ss.val();
  });

  //return Future<int> ss.val();
}

mrn 是键入 int ,应通过 getMrn 方法返回。但是,每次返回的 ss.val()返回 null 。似乎在最后返回的值中没有看到 ss = event.snapshot

mrn is of type int which should be returned by getMrn method. However each time the returned ss.val() returns null. It seems that ss = event.snapshot is not seen in the last returned value

正确的处理方法是这样做。
谢谢

What is the correct way of doing this. Thanks

推荐答案

在上面的代码中,您声明了匿名函数(事件) {..} 作为回调,而您的 return 语句与此相关,而您的意图是 return 来自 getMrn()

In the code above, you're declaring anonymous function (event){..} as a callback, and your return statement relates to it, while your intention was to return from getMrn().

您实际需要的是完成您要从回调中的 getMrn()返回的未来

What are you actually need, is to complete a Future you're returning from getMrn() inside your callback.

就像这样:

Future<int> getMrn() async {
  var mrnRef = await firebaseClient.child('mrn');

  Completer<int> c = new Completer<int>();
  StreamSubscription<Event> onValueSubscription = await mrnRef.onValue
      .listen((event) {
    DataSnapshot ss = event.snapshot;
    c.complete(ss.val());
  });

  return c.future;
}

但如果<$中出现第二个事件,该代码将无法正常工作c $ c> mrnRef.onValue 流。因此,假设 mrnRef.onValue Stream ,并且只需要第一个事件,最好重写它

but that code wouldn't work good if there second event appear in mrnRef.onValue stream. So, assuming mrnRef.onValue is a Stream, and you need only first event, it would be better to rewrite it this way:

Future<int> getMrn() async {
  var mrnRef = await firebaseClient.child('mrn');

  Event event = await mrnRef.onValue.first;
  DataSnapshot ss = event.snapshot;
  // note, you're implicitly returning a Future<int> here,
  // because our function is asyncronous
  return ss.val();
}

这篇关于同步返回值并在dart中等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆