4

In Dart I have a Completer that returns a Future (Promise) and that Future can be completed somewhere else then where it was created, like

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.
  });
}

I don't want a solution for this actual problem, this is only an example I came up with to demonstrate how a Completer is used in Dart. What would be an equivalent to the Dart Completer in TypeScript?

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • What about that: http://stackoverflow.com/questions/27573365/how-to-use-typescript-with-native-es6-promises – LJ Wadowski Jan 08 '16 at 09:52
  • @Etsitra this question/answers don't provide much information. I try to figure out how to use Promise like shown above, where the Promise is created at one place and completed somewhere else. – Günter Zöchbauer Jan 09 '16 at 10:40
  • 1
    I don't know how it would work in TypeScript, but in plain JavaScript, you can store the accept/reject functions somewhere in the promise callback. Something like: `function Completer() { this.promise = new Promise((c,e)=>{this.complete = c; this.completeError = e;}); }`. This creates a completer with a `promise` field, and two functions: `complete` and `completeError`. – lrn Jan 10 '16 at 00:16
  • Thanks @lrn this helped to locate an implementation. – Günter Zöchbauer Jan 10 '16 at 12:28

2 Answers2

10

made this simple class that worked for me:

export class Completer<T> {
    public readonly promise: Promise<T>;
    public complete: (value: (PromiseLike<T> | T)) => void;
    private reject: (reason?: any) => void;

    public constructor() {
        this.promise = new Promise<T>((resolve, reject) => {
            this.complete = resolve;
            this.reject = reject;
        })
    }
}

const prom = new Completer<bool>();

prom.complete(true);
Jonathan
  • 4,724
  • 7
  • 45
  • 65
1

This looks like an implementation of such a Completer in TypeScript https://github.com/angular/angular/blob/b0009f03d510370d9782cf76197f95bb40d16c6a/modules/angular2/src/facade/promise.ts

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};
  }
}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567