【问题标题】:Wait until function returns true等到函数返回 true
【发布时间】:2021-08-15 01:30:19
【问题描述】:

Dart 是否有方法等待函数返回真/假,然后调用它之后的下一个函数?

我在这里看到过类似的问题,但我似乎无法让它们以某种方式工作以实现我的目标。 一些答案使用明确的延迟时间(例如等待 3 秒)。但这不适用于我的方法。

例如

print('START');
await fetchResults(); 
print('COMPLETE'); // This is not called until the fetchResults returns true/false

注意:我尝试过类似的方法:

Future<bool> fetchResults() { 
   await Future.doWhile(() => return true);
}

但这会使我的函数陷入无限循环。

【问题讨论】:

  • Future.doWhile 做你想做的事,但是你的尝试进入了一个无限循环,因为你传递了一个总是返回 true 的函数。使用await Future.doWhile(fetchResults); 等到fetchResults() 返回false,或使用await Future.doWhile(() async =&gt; !await fetchResults()); 等到它返回true
  • 谢谢,我看看我做错了什么。
  • @jamesdlin 我的函数使用一个EventChannel 来监听变化(第三方包)。它是使用诸如showScanner() 之类的函数调用的,但这不会给出回调,因此我无法执行then()。所以我必须想办法改变我的方法。我假设使用Future await,但这不起作用(这就是我得到无限循环的原因。
  • 我不明白。 1. 回调与.then无关。要使用.then,它必须返回一个Future。 2. await.then 的语法糖。 3. 正如我所说,你得到一个无限循环,因为你使用了Future.doWhile 和一个总是返回true 的函数。如果您展示的代码可以重现您尝试解决的问题,这可能会有所帮助。
  • 非常感谢您的澄清,经过研究,我的问题似乎与EventChannel 有关。这是我必须处理事件的地方,毕竟wait 函数不是必需的。

标签: flutter dart asynchronous async-await future


【解决方案1】:

async 函数中,您可以使用await 等待函数调用完成并获得其结果。这将在打印 COMPLETE 之前等待 3 秒:

void waitForIt async {
  print('START');
  if (await (fetchResults())) {
    print('COMPLETE');
  }
}

Future<bool> fetchResults() async {
  return Future.delayed(const Duration(milliseconds: 3000), () {
    return true;
  });
}

但也有可能您的fetchResults 不是异步的,而是同步的。以下产生相同的 3 秒延迟:

import 'dart:io';

bool fetchResults() {
  sleep(Duration(seconds: 3));
  return true;
}

【讨论】:

  • 感谢您的回答。对不起,我觉得有误会,我不想用延时。我说过,因为这是我在网上看到的唯一答案。我的方法与时间一起工作,因为它可以在没有定义延迟的情况下工作,除非通过布尔值。
  • 这只是为了模拟一个需要时间才能完成的真实世界提取。示例经常使用它。如果您提供更多详细信息,也许我可以提供帮助。
  • 这个布尔值是如何收到的?
  • 我正在使用第三方包,它不返回回调或允许任何参数。但它在.receiveBroadcastStream().listen() 的其他地方处理完成,这是调用显式函数的地方,我可以在这里更改布尔值。 showScanner() 可以在任何地方调用。我不想使用特定时间的原因是因为它在扫描仪关闭或扫描成功后给出结果。
【解决方案2】:

你需要为此使用两个异步函数


Future<void> execute()async {
  print('START');
  final result = await fetchResults(); 
  print('COMPLETE'); // This is not called until the fetchResults returns true/false
}


Future<bool> fetchResults() async { 

   // Your fetchResult logic here
   // e.g: 

   final int result = 1+1;
   print('In between'); 
   if(result == 2) return true;
   else return false;
}

输出

START
In between
COMPLETE

【讨论】:

  • 感谢您的回答,我测试一下。
猜你喜欢
  • 1970-01-01
  • 2019-02-20
  • 2017-11-15
  • 1970-01-01
  • 1970-01-01
  • 2019-05-20
  • 1970-01-01
  • 1970-01-01
  • 2014-10-01
相关资源
最近更新 更多