Last active
June 17, 2025 15:40
-
-
Save TuenTuenna/9d13baa86d493aae22b93156bec4a3b5 to your computer and use it in GitHub Desktop.
Dart tip of the day / Lecture 19 / Dart Completer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void main() async { | |
print('시작'); | |
var result1 = await someDelayAsyncFunction(); | |
var result2 = await someDelayAsyncFunction(); | |
someDelayAsyncFunction().then((result ){ | |
}); | |
someDelayAsyncFunction().then((result ){ | |
}); | |
print(result1); | |
multipleCallbackFunction((finalResult) { | |
print(finalResult); | |
}); | |
} | |
Future<String> someDelayAsyncFunction([int delay = 2]) async { | |
var completer = Completer(); | |
Future.delayed(Duration(seconds: delay), () { | |
print('완료 $delay초 경과됨'); | |
completer.complete('완료 $delay초 경과됨'); | |
// completer.isCompleted | |
}); | |
return await completer.future; | |
} | |
void someDelayCallbackFunction( | |
void Function(String) callback, { | |
int delay = 2, | |
}) { | |
Future.delayed(Duration(seconds: delay), () { | |
print('완료 $delay초 경과됨'); | |
callback('완료 $delay초 경과됨'); | |
}); | |
} | |
void multipleCallbackFunction(void Function(List<String>) callback) { | |
var firstCompleter = Completer<String>(); | |
var secondCompleter = Completer<String>(); | |
var thirdCompleter = Completer<String>(); | |
someDelayCallbackFunction(delay: 3, (result1) { | |
firstCompleter.complete(result1); | |
}); | |
someDelayCallbackFunction(delay: 1, (result2) { | |
secondCompleter.complete(result2); | |
}); | |
someDelayCallbackFunction(delay: 2, (result3) { | |
thirdCompleter.complete(result3); | |
}); | |
Future.wait([firstCompleter.future, secondCompleter.future, thirdCompleter.future]) | |
.then((results) { | |
callback(results); | |
}); | |
} | |
Future<List<String>> multipleAsyncFunction() async { | |
var firstCompleter = Completer<String>(); | |
var secondCompleter = Completer<String>(); | |
var thirdCompleter = Completer<String>(); | |
someDelayCallbackFunction(delay: 3, (result1) { | |
firstCompleter.complete(result1); | |
}); | |
someDelayCallbackFunction(delay: 1, (result2) { | |
secondCompleter.complete(result2); | |
}); | |
someDelayCallbackFunction(delay: 2, (result3) { | |
thirdCompleter.complete(result3); | |
}); | |
return Future.wait([firstCompleter.future, secondCompleter.future, thirdCompleter.future]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment