代码如下
Dart
typedef Callback = Function(
Function([dynamic value]) resolve,
Function(Exception error) reject,
);
class Promise {
Promise();
static Future<T?> run<T>([
Callback? callback,
]) async {
final completer = Completer<T>();
//
resolve([value]) {
return completer.complete(value);
}
//
reject(Exception exception) {
completer.completeError(exception);
}
if (callback != null) {
await callback(resolve, reject);
} else {
completer.complete();
}
return completer.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;
}
}
使用方法
Dart
final promise = Promise.run((resolve, reject) {
resolve("finally");
});
核心原理是
利用Future 和Completer。 Future 是异步无状态的 Completer可以返回Future 里面有3种状态
组合一下 就是前端的promise
用法改了一下 使用 Promise.run =》Promise