简体   繁体   中英

Dart's runZoned - how is it different than async await

So I've read the docs and this example in particular:

runZoned(() {
  HttpServer.bind('0.0.0.0', port).then((server) {
    server.listen(staticFiles.serveRequest);
  });
},
onError: (e, stackTrace) => print('Oh noes! $e $stackTrace'));

I understand the whole zone-local-values thing, and the sort of AOP option of tracing code through a zone - enter/exit.

But other than that, is the code block above any different than:

try {
  var server = await HttpServer.bind('0.0.0.0', port);
  server.listen(staticFiles.serveRequest);
} catch (error) {
  print('Oh noes! $e ${e.stackTrace}');
}

Thanks:)

The runZoned code introduces a new uncaught error handler.

Some asynchronous errors do not happen in a context where they can be thrown to user code. For example, if you create a future, but never await it or listen to it in any other way, and that future then completes with an error, that error is considered "uncaught" or "unhandled". Futures work using callbacks, and there has been no callback provided that it can call.

In that case, the current zone's uncaught error handler is invoked with the error.

Your first example introduces such a handler, which means that if the body of the runZoned call has any uncaught async errors, you'll be told about them. That includes the future returned by calling then , but also any other asynchronous errors that may happen (if any).

When you await a future, and that future completes with an error, that error is (re)thrown, an can be caught. The try / catch of the second example will catch that error (and any thrown by calling listen , which shouldn't be any as long as server isn't null , which it shouldn't be).

So, the difference is only really in whether uncaught asynchronous errors are handled. (And how any errors in the catch code is propagated, because an error happening during an uncaught-error zone handler will again be uncaught.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM