美文网首页
Flutter中Dart语言的async/await

Flutter中Dart语言的async/await

作者: RookieRun | 来源:发表于2021-11-26 11:48 被阅读0次
    Dart中的async/await与C#等其他语言中的用法相似,这也让那些有过这些语言使用经验的人很容易上手。
    然而,即使你没有过任何使用async/await异步编程的经验的话,你也会发现Dart中的async/await也是非常容易上手的。
    只要记住这里的async/await和其他异步编程语言有最基本的一致性就行了。
    首先,你要先理解两个关键字,就是async和await,你想要运行的任何一个异步函数都要在函数签名上增加async这个关键字。
    这个关键字是在函数的右边,紧跟函数名:
    
        void hello() async {
            print('something exciting is going to happen here...');
        }
    

    当然,你想要异步运行的函数可能会有很多其他的操作(比如文件I/O,或者网络操作),别急,我会在接下来说:
    第一,我们先来说await,这个关键字的意思就是说:继续然后异步执行这个函数,函数执行完毕后,继续执行下一行代码。
    下面的部分代码就是async/await用法的最好的解释,你也可以参考着这么写:

        void main() async {
            await hello();
            print('all done');
        }
    
    上面的这段代码有两点需要着重注意:
        1.我们在main函数上注明了async关键字,因为,我们要异步执行hello方法
        2.我们把await关键字直接放到了我们要异步执行的方法的前面,所以,这也是我们最常用的async/await组合方式。
    你只需要记住,只要你想用await,那么就要确认所有调用的方法以及任何这个方法里面调用的方法都要用async注明
    那么async/await是怎么工作的呢?
        1.当你await任何异步函数的时候,调用者的代码的执行就会挂起,这个时候,async方法正在被执行。当async 操作执行完毕后,
        await的执行结果会包含在一个Future对象中返回。
        2.看下下面这个简单的例子,我们把four()这个函数的返回值是赋值给了变量X,然后,我们打印看看是不是我们想要的结果
    
            import 'dart:async';
            void main() async {
                var x = await four();
                print(x);
            }
    
            Future<int> four() async {
                return 4;
            }
    
    ### 一个更实际的例子
    
         其实,你想要异步执行过代码的原因就是你知道你要执行一段运行时间比较长的函数,然而你不希望在函数执行期间程序对用户的操作没有任何反应。我们创建了一个耗时2s的函数,然后异步执行。
    
            import 'dart:async';
    
            class Employee {
            int id;
            String firstName;
            String lastName;
            
            Employee(this.id, this.firstName, this.lastName);
            }
    
            void main() async {
                print("getting employee...");
                var x = await getEmployee(33);
                print("Got back ${x.firstName} ${x.lastName} with id# ${x.id}");
            }
    
            Future<Employee> getEmployee(int id) async {
                //Simluate what a real service call delay may look like by delaying 2 seconds   
                await Future<Employee>.delayed(const Duration(seconds: 2));
                //and then return an employee - lets pretend we grabbed this out of a database 🙂
                var e = new Employee(id, "Joe", "Coder");
                return e;
            }
    
        如果你运行上面的代码,你就会马上看到“getting employee”打印出来,然后2s之后,employee返回然后打印出详细信息。
    
    ### 多个异步调用
    
        在有些编程语言中,如果他们不支持async/await语法而不得不做多个异步调用是一个很头疼的事情,这是因为,你要先做第一个异步调用然后在第二个,第三个。。。,这也就是所谓的回调地狱。
        然而,有了async/await,你就可以线性的调用而不用潜逃,就像写非异步代码那样。
        看看你下面的代码,我们有三个异步的方法,然后我们想同时,按顺序异步调用他们。
    
            import 'dart:async';
    
            Future<String> firstAsync() async {
                await Future<String>.delayed(const Duration(seconds: 2));
                return "First!";
            }
    
            Future<String> secondAsync() async {
                await Future<String>.delayed(const Duration(seconds: 2));
                return "Second!";
            }
    
            Future<String> thirdAsync() async {
                await Future<String>.delayed(const Duration(seconds: 2));
                return "Third!";
            }
    
            void main() async {
            var f = await firstAsync();
            print(f);
            var s = await secondAsync();
            print(s);
            var t = await thirdAsync();
            print(t);
            print('done');
            }
    
       打印结果:
        First!
    
        Second!
    
        Third!
    
        done
    

    参考:https://www.educative.io/edpresso/darts-async-await-in-flutter

    相关文章

      网友评论

          本文标题:Flutter中Dart语言的async/await

          本文链接:https://www.haomeiwen.com/subject/zsgtxrtx.html