在特定时间等待未来 [英] Await future for a specific time

查看:30
本文介绍了在特定时间等待未来的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您将如何等待特定时间的未来响应?

How would you wait for future response for a specific amount of time?

比如说,我们发出一个 http post 请求并在我们关闭 http 请求之前等待它的响应,但是,我们只等待 3 秒,否则我们关闭请求.

Say, we make a http post request and await for its response before we close the http request, but, we wait for only 3 secs, else we close the request.

您将如何实现这一目标?

How would you achieve that?

类似的东西

Future makePostReq() async{
  .... 

  await http response for 3 secs

  .... 

 if(response) {
  ... Do something with it
 }

 Http.close

} 

推荐答案

您可以使用 Future.any 构造函数来制造竞争条件

You can use Future.any constructor to make a race condition

final result = await Future.any([
  Future.value(42),
  Future.delayed(const Duration(seconds: 3))
]);

你也可以使用Future.timout 方法

You can also use Future.timout method

final result = await Future.value(42).timeout(const Duration(seconds: 3));

这篇关于在特定时间等待未来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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