如何在Dart中实现async / await

时间:2015-11-17 04:05:19

标签: dart dart-async

我想我理解 async 背后的想法,返回Future,但我不清楚 async 在非常基本的层面上的行为。根据我的理解,它不会自动在程序中创建异步行为。例如:

import 'dart:async';
main() {
  a();
  b();
}
a()  {
  new Timer(new Duration(milliseconds: 20), () {});  // create latency
  print("a");
}
b()  {
  print("b");
}
// a
// b

如果在a()之后放置 async ,则首先异步执行b(),并在给定的延迟后执行();

import 'dart:async';
main() {
  a();
  b();
}
a() **async** {
  new Timer(new Duration(milliseconds: 20), () {});  // create latency
  print("a");
}
b()  {
  print("b");
}
// b 
// a

但如果你在a()和b()之后放置 async ,则首先执行a(),类似于根本不使用 async

import 'dart:async';
main() {
a();
b();
}
a() **async** {
  new Timer(new Duration(milliseconds: 20), () {});  // create latency
  print("a");
}
b() **async** {
  print("b");
}
//a
//b

在所有功能上使用 async 完全取消 async 功能吗?

现在,我认为main() async 实际上并没有自动激活异步行为。如果在main()之后添加 async ,则不会发生任何变化。但是,它允许您使用等待,以防您在继续程序之前必须等待a()函数先完成。这是对的吗?

import 'dart:async';
main() **async** {
  **await** a();
  b();
}
a() **async** {
new Timer(new Duration(milliseconds: 20), () {});  // create latency
print("a");
}
b() {
print("b");
}
// waits for the value of a() if you put **await** keyword
// a
// b

但是,我看到main() async {}以及在脚本html标记之后使用它,但在任何地方都没有等待。在不同的背景下它是否意味着不同的东西?我希望我已经充分解释了逻辑。你能解释一下我是如何误解async / await的使用的吗?谢谢。

1 个答案:

答案 0 :(得分:2)

a()  {
  new Timer(new Duration(milliseconds: 20), () {});  // create latency
  print("a");
}

此代码不会延迟执行print("a"); 20 ms。它只是延迟了{}的执行,该print("a");被排队以便以后执行,然后立即继续async

使用await / async的代码和不含await / import 'dart:async'; main() async { await a(); b(); await main2(); // call the example without async/await } Future a() async { await new Future.delayed(const Duration(milliseconds: 20), () {}); // create latency print("a"); } void b() { print("b"); } Future main2() { return a2().then((_) { b(); }); } // equivalent of a without async/await Future a2() { return new Future.delayed(const Duration(milliseconds: 20), () {}) // create latency .then((_) => print("a")); } 的等效代码如下所示:

\brief Start the SimpleLink device

This function initialize the communication interface, set the enable pin 
of the device, and call to the init complete callback.

\param[in]      pIfHdl              Opened Interface Object. In case the interface 
                                    must be opened outside the SimpleLink Driver, the
                                    user might give the handler to be used in \n
                                    any access of the communication interface with the 
                                    device (UART/SPI). \n
                                    The SimpleLink driver will open an interface port
                                    only if this parameter is null! \n
\param[in]      pDevName            The name of the device to open. Could be used when 
                                    the pIfHdl is null, to transfer information to the 
                                    open interface function \n
                                    This pointer could be used to pass additional information to
                                    sl_IfOpen in case it is required (e.g. UART com port name)
\param[in]      pInitCallBack       Pointer to function that would be called
                                    on completion of the initialization process.\n
                                    If this parameter is NULL the function is 
                                    blocked until the device initialization 
                                    is completed, otherwise the function returns 
                                    immediately.

\return         Returns the current active role (STA/AP/P2P) or an error code:
                - ROLE_STA, ROLE_AP, ROLE_P2P in case of success, 
                  otherwise in failure one of the following is return:
                - ROLE_STA_ERR  (Failure to load MAC/PHY in STA role)
                - ROLE_AP_ERR  (Failure to load MAC/PHY in AP role)
                - ROLE_P2P_ERR  (Failure to load MAC/PHY in P2P role)


 \sa             sl_Stop

\note           belongs to \ref basic_api

\warning        This function must be called before any other SimpleLink API is used, or after sl_Stop is called for reinit the device
\par            Example:
\code            
               An example for open interface without callback routine. The interface name and handler are
               handled by the sl_IfOpen routine: 

                if( sl_Start(NULL, NULL, NULL) < 0 )
               {
                   LOG("Error opening interface to device\n"); 
               }
\endcode

#if _SL_INCLUDE_FUNC(sl_Start)
_i16 sl_Start(const void* pIfHdl, _i8*  pDevName, const P_INIT_CALLBACK pInitCallBack);
#endif

试试DartPad