代码如下
typedef Callback = Function(
Function([dynamic value]) resolve,
Function(Exception error) reject,
);
class Promise {
Promise();
static Future<T?> run<T>([
Callback? callback,
]) async {
final ***pleter = ***pleter<T>();
//
resolve([value]) {
return ***pleter.***plete(value);
}
//
reject(Exception exception) {
***pleter.***pleteError(exception);
}
if (callback != null) {
await callback(resolve, reject);
} else {
***pleter.***plete();
}
return ***pleter.future;
}
static Future<T?> resolve<T>([T? value]) async {
await Future.delayed(Duration.zero);
return value;
}
static Future<T> reject<T extends Exception>(T value) async {
await Future.delayed(Duration.zero);
throw value;
}
}
使用方法
final promise = Promise.run((resolve, reject) {
resolve("finally");
});
核心原理是
利用Future 和***pleter。 Future 是异步无状态的 ***pleter可以返回Future 里面有3种状态
组合一下 就是前端的promise
用法改了一下 使用 Promise.run =》Promise