我喜欢在我的Dart应用程序中模拟一个异步web服务调用进行测试。为了模拟这些模拟调用响应的随机性(可能是无序的),我想编程我的模拟在返回“Future”之前等待(睡眠)一段时间。
我该怎么做呢?
我喜欢在我的Dart应用程序中模拟一个异步web服务调用进行测试。为了模拟这些模拟调用响应的随机性(可能是无序的),我想编程我的模拟在返回“Future”之前等待(睡眠)一段时间。
我该怎么做呢?
当前回答
我发现在Dart中有几个实现可以使代码延迟执行:
new Future.delayed(const Duration(seconds: 1)); //recommend
new Timer(const Duration(seconds: 1), ()=>print("1 second later."));
sleep(const Duration(seconds: 1)); //import 'dart:io';
new Stream.periodic(const Duration(seconds: 1), (_) => print("1 second later.")).first.then((_)=>print("Also 1 second later."));
//new Stream.periodic(const Duration(seconds: 1)).first.then((_)=>print("Also 1 second later."));
其他回答
你可以这样用:
sleep(Duration(seconds: 5));
Or
Future.delayed(const Duration(seconds: 5));
2019年版:
异步代码
await Future.delayed(Duration(seconds: 1));
同步代码
import 'dart:io';
sleep(Duration(seconds:1));
注意:这将阻塞整个进程(隔离),因此其他异步函数将不会被处理。它也不能在网络上使用,因为Javascript是纯异步的。
这是一个有用的模拟,可以接受一个可选参数来模拟错误:
Future _mockService([dynamic error]) {
return new Future.delayed(const Duration(seconds: 2), () {
if (error != null) {
throw error;
}
});
}
你可以这样使用它:
await _mockService(new Exception('network error'));
如果你需要在一段时间后执行一些代码
Future.delayed(const Duration(seconds: 5), () {
//do something
});
我发现在Dart中有几个实现可以使代码延迟执行:
new Future.delayed(const Duration(seconds: 1)); //recommend
new Timer(const Duration(seconds: 1), ()=>print("1 second later."));
sleep(const Duration(seconds: 1)); //import 'dart:io';
new Stream.periodic(const Duration(seconds: 1), (_) => print("1 second later.")).first.then((_)=>print("Also 1 second later."));
//new Stream.periodic(const Duration(seconds: 1)).first.then((_)=>print("Also 1 second later."));