赞
踩
代码如下
- 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;
- }
- }
使用方法
- final promise = Promise.run((resolve, reject) {
- resolve("finally");
- });
核心原理是
利用Future 和Completer。 Future 是异步无状态的 Completer可以返回Future 里面有3种状态
组合一下 就是前端的promise
用法改了一下 使用 Promise.run =》Promise
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。