Dart异步/等待内部 [英] Dart async/await internals

查看:87
本文介绍了Dart异步/等待内部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在搜索 async/await 实现的来源.

I'm searching for the source of async/await implementations.

我想知道它们是如何工作的,以便侵入 future.then()来检测是否有等待执行的代码.

I would like to know how do they truly works in order to hack into future.then() to detect if there is code awaiting for execution or not.

修改

这是我愿意完成的事情:

This is what I'm willing to accomplish:

TrackingCompleter completer = new TrackingCompleter();
TrackingFuture future = completer.future;
print("isAwaited: ${future.isAwaited} (F)");
new Future.delayed(new Duration(milliseconds: 500), () {
  future.then((_) {
    print("executing sorping");
    print("isThenExecuted: ${future.thenExecuted} (F)");
    new Future.delayed(new Duration(milliseconds: 500), () {
      print("isThenExecuted: ${future.thenExecuted} (T)");
      exit(1);
    });
  });
  print("isAwaited: ${future.isAwaited} (T)");
  print("isThenExecuted: ${future.thenExecuted} (F)");
  completer.complete();
});

到目前为止,这是可行的.我现在想做的是检测 future.then 是在代码中手动调用还是通过 await 语句自动调用.

As far, that's working. What I'd like to do now is to detect if future.then is called manually in the code or automatically with an await statement.

推荐答案

async/await实现基于期货.基本上, await 创建一个包含当前函数其余部分的函数(await表达式的"continuation"),然后在以后使用该函数等待的将来调用 then 作为参数.处理错误还需要更多细节,但基本上就是这些.

The async/await implementation is based on futures. Basically, await creates a function that contains the rest of the current function (the "continuation" of the await expression), and then calls then on the future you await with that function as argument. There are more details needed to handle errors, but that's basically it.

在您的情况下,如果您想知道是否调用 future.then ,我建议只包装该特定的将来.示例:

In your case, if you want to know if future.then is called, I recommend just wrapping that particular future. Example:

import "package:async/async.dart";

class ThenWrapper<T> extends DelegatingFuture<T> {
  void Function(S Function(T), S Function(Object, StackTrace)) _callback;
  ThenWrapper(Future<T> future, this._callback): super(future);
  Future<S> then<S>(S onValue(T), {S onError(error, StackTrace st)}) {
    _callback(onValue, onError);
    return super.super(onValue, onError);
  }
}
...

TrackingFuture future = new ThenWrapper(completer.future, ...);

您可以更改回调以执行所需的任何操作.

You can change the callback to do whatever you want.

这篇关于Dart异步/等待内部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆