在Dart中,我有一个Completer,它返回一个Future( promise ),并且Future可以在创建它的其他位置完成,例如

class SomeClass {
  final Completer<bool> initializationDone = new Completer<bool>();

  SomeClass() {
    _doSomeAsyncInitialization();
  }

  void _doSomeAsyncInitialization() {
    // some async initialization like a HTTP request
    fetchDataFromServer().then((data) {
      processData();
      initializationDone.complete(true);
    });
  }
}

main() {
  var some = new SomeClass();
  some.initializationDone.future.then((success) {
    // do something.
  });
}

我不想要解决这个实际问题的方法,这只是我想出的一个示例,用于演示Dart中如何使用Completer
相当于TypeScript中的Dart Completer

最佳答案

这看起来像是TypeScript https://github.com/angular/angular/blob/b0009f03d510370d9782cf76197f95bb40d16c6a/modules/angular2/src/facade/promise.ts中这种Completer的实现

export {Promise};

export interface PromiseCompleter<R> {
  promise: Promise<R>;
  resolve: (value?: R | PromiseLike<R>) => void;
  reject: (error?: any, stackTrace?: string) => void;
}

export class PromiseWrapper {
  static resolve<T>(obj: T): Promise<T> { return Promise.resolve(obj); }

  static reject(obj: any, _): Promise<any> { return Promise.reject(obj); }

  // Note: We can't rename this method into `catch`, as this is not a valid
  // method name in Dart.
  static catchError<T>(promise: Promise<T>,
                       onError: (error: any) => T | PromiseLike<T>): Promise<T> {
    return promise.catch(onError);
  }

  static all(promises: any[]): Promise<any> {
    if (promises.length == 0) return Promise.resolve([]);
    return Promise.all(promises);
  }

  static then<T, U>(promise: Promise<T>, success: (value: T) => U | PromiseLike<U>,
                    rejection?: (error: any, stack?: any) => U | PromiseLike<U>): Promise<U> {
    return promise.then(success, rejection);
  }

  static wrap<T>(computation: () => T): Promise<T> {
    return new Promise((res, rej) => {
      try {
        res(computation());
      } catch (e) {
        rej(e);
      }
    });
  }

  static scheduleMicrotask(computation: () => any): void {
    PromiseWrapper.then(PromiseWrapper.resolve(null), computation, (_) => {});
  }

  static isPromise(obj: any): boolean { return obj instanceof Promise; }

  static completer(): PromiseCompleter<any> {
    var resolve;
    var reject;

    var p = new Promise(function(res, rej) {
      resolve = res;
      reject = rej;
    });

    return {promise: p, resolve: resolve, reject: reject};
  }
}

08-06 03:17