Dart의 Future는 지금은 없지만 미래에 요청한 데이터 혹은 에러가 담길 그릇이다.
Future는 싱글스레드 환경에서 비동기처리를 위해 존재한다.
Future<String> helloWorld() {
return Future<String>.delayed(Duration(seconds: 3), () {
return "success";
});
}
...
final str = helloWorld();
str.then((val) {
print("HelloWorld");
}).catchError((error) {
print("ERROR!!!");
});
print("wait...");
Future<String>의 뜻은 나중에 String 혹은 error가 나온다는 이야기이다.
-> then, catchError 함수로 컨트롤할 수 있다.
Future<String>은 Future 에서 String으로 바뀌는 것이 아니라,
계속해서 Future<String>이다.
wait...
HelloWorld
Future<String> HelloWorld() async {
... await Func1();
... await Func2();
return "HelloWorld";
}
final str = await HelloWorld();
HelloWorld() 함수 실행.str 변수에는 Future가 담김.Func1(), Func2() 순차적으로 실행한 후에 HelloWorld return 함.str 변수에는 HelloWorld가 담김.then() 함수는 수행 중인 함수를 중간에 멈추도록 하지 않음.async/await 키워드는 수행 중인 함수를 중간에 동작이 완료될 때까지 멈춤.// Func1
Future<String> func1() {
return Future.delayed(Duration(seconds: 3), () {
return "1";
});
}
// Func2
Future<String> func2() {
return Future.delayed(Duration(seconds: 3), () {
return "2";
});
}
// Func3
Future<String> helloWorld() async{
final hello1 = await func1();
print("$hello1"); // print
final hello2 = await func2();
print("$hello2"); // print
print("제일 빨리 출력하고픔"); // print
}
final helloworld = helloWorld();
print("first"); // print
first // 0초
1 // 3초
2 // 6초
제일 빨리 출력하고픔 // 6초
helloworld 변수 자체가 await이 아니므로 비동기처리로 first 출력.helloWorld() 함수 실행func1() 함수 끝날 때까지 대기1 출력await func2() 함수 끝날 때까지 대기2, 제일 빨리 출력하고픔 출력제일 빨리 출력하고픔은 앞에 있는 await 때문에 값을 참조하지 않음에도 불구하고 가장 마지막에 실행되었다.
// Func1
Future<String> hello1() {
return Future.delayed(Duration(seconds: 3), () {
return "1";
});
}
// Func2
Future<String> hello2() {
return Future.delayed(Duration(seconds: 3), () {
return "2";
});
}
// Func3
Future<String> helloWorld() {
final hello1 = hello1();
hello1.then((val) => print("$val")); // print
final hello2 = hello2();
hello1.then((val) => print("$val")); // print
print("제일 빨리 출력하고픔"); // print
}
final helloworld = helloWorld();
print("first"); // print
제일 빨리 출력하고픔 // 0초
first // 0초
1 // 3초
2 // 6초
대부분의 경우 asyc/await으로 대체가 되지만,
위와 같은 경우에는 then() 키워드를 사용할 수 있다.
따라서 async/await으로 완전히 대체하지는 못하지만 대부분을 대체할 수 있다.
출처
1