flutter中提供了Future.wait()函数,可以在执行多个异步请求之后有一个统一的回调结果,但是劣势在于,每一个异步函数的函数体中都需要执行return去返回结果,如果在异步请求中,有多层success或者fail这种函数的嵌套,那么可能会在某个地方忽略掉retrun,导致没有办法拿到正确的结果。所以这里封装了一个类似于js中Promise中的类去执行多个异步请求。
- Promise Class代码如下
class Promise {
Future future;
static Future all(List<Promise> promises) async{
var items = promises.map((promise) {
return promise.then((value) {
return Future.delayed(Duration(seconds: 0), () {
return value;
});
});
}).toList();
return await Future.wait(items);
}
Promise(dynamic execute(dynamic resolve(val), dynamic reject(val))) {
if (!(execute is Function)) {
throw new AssertionError('execute params type is error');
}
final completer = Completer();
try {
execute(completer.complete, completer.completeError);
} catch (e) {
completer.completeError(e);
}
this.future = completer.future;
}
Future then(Future Function(dynamic) onValue, {Function onError}) {
return this.future?.then(onValue, onError: onError);
}
}
调用方式如下:
{
var p1 = method1();
var p2 = method2();
Promise.all([p1, p2]).then((value) {
print(value);
}).catchError((e) {
print('出错了$e');
});
}
Promise method1() {
Promise promise = Promise((resolve, reject) {
Future.delayed(Duration(seconds: 3), () {
resolve("hello");
});
});
return promise;
}
Promise method2() {
Promise promise = Promise((resolve, reject) {
Future.delayed(Duration(seconds: 2), () {
resolve("world");
});
});
return promise;
}