skip to Main Content

Why does not "await" work?

Future<void> f1() async{
  Future.delayed(Duration(seconds:2), (){
    print('f1');
  });
}

void main() async{
  print('start');
  await f1();
  print('end');
}

output

start
end
f1

but await working in next code.

Future<void> f1() async{
  return Future.delayed(Duration(seconds:2), (){
    print('f1');
  });
}

void main() async{
  print('start');
  await f1();
  print('end');
}

output

start
f1
end

why????

I dont understand…..

3

Answers


  1. Because in the first code block f1() is awaited and it’s child Future is not. In the second it’s returned. If you want to wait for the delayed Future, await it as well. Like so

    Future<void> f1() async{
     await Future.delayed(Duration(seconds:2), (){
        print('f1');
      });
    }
    
    void main() async{
      print('start');
      await f1();
      print('end');
    }
    
    
    Login or Signup to reply.
  2. because the in the first one, you only interupt for the f1,

    to make you better understanding see this

    Future<void> f1() async{
      Future.delayed(Duration(seconds:2), (){
        print('f1');
      });
      print("---done---");
    }
    
    void main() async{
      print('start');
      await f1();
      print('end');
    }
    

    result:

    start
    ---done---
    end
    f1
    

    the f1 has been done executed, the Future.delayed has been on the
    queue, but since its not use await then its not interupt the proces.
    the next one print('end') will be executed.


    but if you also add await inside the f1 , it will interupt the process

    Future<void> f1() async{
      await Future.delayed(Duration(seconds:2), (){
        print('f1');
      });
      print("---done---");
    }
    
    

    result:

    start
    f1
    ---done---
    end
    

    in the second one, since you are returning the Future.delayed which mean, it direclty execute the Future.delayed and interupt the process.

    Login or Signup to reply.
  3. You need to either await Future.delayed or return Future.delayed. The f1 call in the main expects a Future object to be returned which it can await.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search