DEV Community

loading...

Async,Future,Await

moaz mahmoud saad
・1 min read

what is asynchronous operations?
asynchronous operations allow the program to complete work while waiting for operation to finish
example:
reading data from database
getting data from an API
, and many other operations

what if we didn't use Asynchronous keywords?
it may cause run time error as no returned value comes from the method as it need this key words
(Async,Future,Await) that will make the program wait until the function finish it's work and return the value

what is the diffrence between Future and future ?
future is a keyword that instantiated from class Future
and future has two states

1-complete - it's the state that means the function finish it work either return a value or throw an error and the returned value
is Future where T is any datatype or object

2-uncomplete - When you call an asynchronous function, it returns an uncompleted future. That future is waiting for the function’s asynchronous operation to finish or to throw an error.

how to work with future , async , await ?
async: You can use the async keyword before a function’s body to mark it as asynchronous.

await: You can use the await keyword to get the completed result of an asynchronous expression

and the return will be Future where T is any datatype or object

example of converting main function to asynchronous method:
Future main () async { await print("hello world");}

how this keywords effect the execution of code?
the async function body executes like synchronous functions until the first wait which means all the code lines before await executes immediately

Discussion (0)