Enhancement Request: Add '.toFuture()' or '.toAsync()' as default method for all Function types #2705

Closed
DartBot opened this Issue Apr 23, 2012 · 5 comments

5 participants

@DartBot
Dart member

This issue was originally filed by prujo...@gmail.com


I find myself writing a function-to-future wrapper in most of my non-trivial projects.

Putting forward for consideration that it makes sense to just add a standard conversion to Future method on all Function types.

Thanks,
John

@DartBot
Dart member

This comment was originally written by jat@google.com


And what would the implementation look like? How would it convert the synchronous body of the function into an async one?

@madsager
Dart member

Removed Type-Defect label.
Added Type-Enhancement, Area-Language, Triaged labels.

@DartBot
Dart member

This comment was originally written by prujoh...@gmail.com


@jat I'm just a simple caveman, but this is how I approach it:

  Future f2f(Function f){
    Completer c = new Completer();
    
    doIt() {
      c.complete(f());
    }
    
    try{
      window.setTimeout(doIt, 0);
    }catch (Exception e){
      c.completeException(e);
    }
    
    return c.future;
  }
  
  String expensiveFunc(int ms){
    var time = new Date.now();
    var nextTime = time;
    while(nextTime.difference(time).inMilliseconds < ms){
      nextTime = new Date.now();
    }
    return "Expensive function finished.";
  }
  
  f2f(() => expensiveFunc(5000)).then((v) => print(v));
  
  print('I print first.');

  // instead it would be nice if f2f() was standard method of Function...
  // expensiveFunc(5000).toFuture().then((v) => print(v));
  //
  // also perhaps option to direct to a thread pool (wrapped in a Isolate [constrained that func must return isolate-legal value])
  // expensiveFunc(5000).toIsolate().then((v) => print(v));

@gbracha

Removed Area-Language label.
Added Area-Library label.

@sethladd
Dart member

Thanks for the suggestion! Implemented with Future.of()


Added this to the M4 milestone.
Added Fixed label.

@DartBot DartBot added this to the M4 milestone Apr 8, 2013
This issue was closed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment