代码如下
typedef Callback = Function(Function([dynamic value]) resolve,Function(Exception error) reject,);class Promise {Promise();static Future run([Callback? callback,]) async {final completer = Completer();//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 resolve([T? value]) async {await Future.delayed(Duration.zero);return value;}static Future reject(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