2022년 10월 23일 일요일

[Flutter] Future, async, await 사용방법

 async 는 비동기 명령사용시 함수에 사용합니다.

비동기 명령은 네트워크통신으로 서버에서 데이터를 요청할 때 또는 delay time이 필요한 명령을 사용할때 사용합니다.

비동기 명령을 사용하는 이유는, 처리시간이 걸리는 명령(코드)에서 메인쓰레드를 잡아 기다리게하지 않고, 별도 쓰레드에서 처리하기 위해서 입니다. 비동기 명령을 통해, 메인쓰레드에서 하는 터치또는 화면표시 렌더링은 비동기명령 처리 시 기다리지 않고 처리됩니다.

await을 설명하겠습니다. 비동기 명령을 사용하는 함수에서 async를 붙여 사용하는데, 비동기명령을 실행 할 때 await를 명령 또는 함수 앞에 붙여주면, 해당 async 붙인 함수 내에서는 await 를 붙인 함수가 실행될때 까지 기다린 후, 다음 명령을 실행합니다.

Future 는 async 를 붙인 함수의 return값을 반환할때 반환형에 함께 붙여 사용합니다.


---- test code ----

void main() {

    print('test 1');

    print('name: ${getName()}');

    print('test 2');

}

Future<String> getName() async {

    print('test 3');

    var name = await requestName();

    print('test 4');    

    return name;

}

---- run result ----

test1

test2

test3

test4






---- english ----


async is used for functions when using asynchronous commands.


Asynchronous commands are used when requesting data from the server through network communication or when using commands that require delay time.


The reason for using asynchronous commands is to process them in a separate thread, rather than waiting for the main thread to wait for commands (code) that take time to process. With an asynchronous command, the touch or display rendering done in the main thread is processed without waiting when processing the asynchronous command.


Let me explain await. Async is used in a function that uses an asynchronous command. When executing an asynchronous command, if await is added before a command or function, the async function waits until the awaited function is executed and then executes the next command. .


Future is used together with the return type when returning the return value of a function to which async is attached.





댓글 없음:

댓글 쓰기